如何使用 yii 框架从 URL 中隐藏 user_id? [英] How can I hide user_id from URL using yii framework?
问题描述
我正在使用 yii 框架并且有不同的用户帐户.当我想查看用户 4 的视图页面时,我必须输入一个类似 www.mydomain.com/user/4
的 url 进行更新,我有 www.mydomain.com/用户/更新/4
.
I am using the yii framework and have different user accounts. When I want to have a look at the view page of user 4 I have to enter an url like www.mydomain.com/user/4
for update I have www.mydomain.com/user/update/4
.
有没有办法让我可以从 url 行中隐藏用户 ID?
Is there a way so that I can hide the user id from the url line?
如何设置像 www.mydomain.com/user/username
和 www.mydomain.com/user/update/username
这样的路由?我必须修改路线吗?
How can I set a route like www.mydomain.com/user/username
and www.mydomain.com/user/update/username
? Do I have to modify the routes?
如果 username
包含 @ 符号怎么办?
What if the username
contains an @ symbols?
推荐答案
如果每个用户都有唯一的用户名,您可以通过将此自定义路由规则放在 config/中来描述不显示其用户 ID 的路由主要
:
If each user has a unique username, you can describe a route that doesn't show their user id by putting this custom routing rule in config/main
:
'urlManager' => array(
'rules' => array(
'user/<username:\S+>' => 'users/view',
)
)
\S+
应该接受@".然后将该用户名传递给 controllers/UsersController
,如下所示:
The \S+
should accept "@". Then pass that username to controllers/UsersController
like so:
public function actionView($username) {...}
而不是 www.mydomain.com/user/update/username
我会使用 www.mydomain.com/user/
并把这个在上面的 urlManager 规则数组中:
Instead of www.mydomain.com/user/update/username
I would use www.mydomain.com/user/<username>/update
and put this in the above urlManager rules array:
'user/<username:\S+>/update' => 'users/update',
在 UsersController
中:
public function actionUpdate($username) {...}
您还可以在创建和路由之前为每个用户生成一个唯一的随机数.
You can also generate a unique, random number for each user before creation and route based on that number.
这篇关于如何使用 yii 框架从 URL 中隐藏 user_id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!