如何使用 Yii 框架像 Quora 那样制作 url slug ?
使用 Quora 让我想知道他们是如何做这样的 slug 的:quora.com/topics-slugs、quora.com/questions-slug 或 quora.com/usernames-slug。
实际上我正在使用 yii 框架开发一个应用程序,我想要一个像 quora 那样的 slugs?
谢谢大家
Using Quora has made me wonder how they do their slug like thes : quora.com/topics-slugs , quora.com/questions-slug or quora.com/usernames-slug.
Actually i am developing an application with yii framework and i want to have a slugs like quora does?
Thanks guys
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您也可以通过重写规则来做到这一点。在你的配置文件中这样的规则:
将采用这样的 URL:
它将重定向到控制器中的 actionView() ,并将 slug (“my-slug”) 作为 $_GET 变量传递。使用该重写规则,您现在调用 $_GET['slug'] ,它将从 url 返回“my-slug”。
我有一个“slug”行作为主键,所以我只需在 actionView() 中查询数据库中的 $_GET['slug'] ,然后根据 URL 获得正确的记录。就像魅力一样。祝你好运!
更新
除了使用 slug 之外,要摆脱控制器前缀,您可能需要一张大表来跟踪所有 url slug(以防止重复)。如果你有,那么你可以做一些不同的事情:
1 覆盖 onBeginRequest< /a> 在 master slug 表上进行查找以找出要调用的控制器。
2. 对 SiteController 中的单个 ActionIndex 使用主重写,并在该操作中查找主表中的 slug 以找出将用户发送到哪个控制器/操作。重写规则看起来像这样:
You can also do this with rewrite rules. A rule like this in your config file:
will take a URL like this:
and it will redirect to the actionView() in your Controller, and pass the slug ("my-slug") in as a $_GET variable. With that rewrite rule you now call $_GET['slug'] and it will return "my-slug" from the url.
I have a "slug" row as a primary key so then I just query the DB for $_GET['slug'] in my actionView() and I get the correct record based on the URL. Works like a charm. Good luck!
UPDATE
To get rid of the controller prefix in addition to using a slug, you will probably need one large table to keep track of all url slugs (to prevent duplicates). If you have that, then you could do a couple of different things:
1 Override onBeginRequest to do a lookup on the master slug table to figure out which Controller to call.
2. Use a master rewrite to a single ActionIndex in the SiteController, and in that action look up the slug in the master table to figure out which controller/action to send the user to. The rewrite rule would look something like this:
像这样的例子:
Something like that for example:
这可能对您有帮助: dburlmanager
This may help you: dburlmanager