YII 框架用户友好 URL [英] YII framework user friendly URL
问题描述
我的 yii PHP 项目有 UserController,它有一个名为 actionView 的操作.我可以使用以下 URL 访问用户查看页面
My yii PHP project has UserController and it has an action called actionView. I can access user view page using following URL
mysite.com/user/view/id/1
我想把那个改成
mysite.com/username
我该怎么做.
我知道我可以简单地创建规则来对用户更友好,以获取诸如
I know that i can simply create rule to be more user friendly to get url such as
mysite.com/user/username
但是以数据库资源名称作为直接参数 (mysite.com/username
) 的 url 方案是完全不同的故事.
But url scheme with database resource name as direct param (mysite.com/username
) is whole different story.
推荐答案
Url rule:
array(
'<username:\w+>'=>'user/view',
)
请注意,在这种方案中,您还必须为所有控制器创建规则并将规则放在最后,因此最好以用户为前缀:
Note that in such scheme, you must also create rules for all your controllers and place above rule at the end, so better prefix it with user:
array(
'user/<username:\w+>'=>'user/view',
)
结果 url 将是 example.com/user/username
在行动:
public function actionView($username) ...
更新:要创建对任何输入变量做出反应的规则,请创建自定义 url 规则类,以下是一些示例,请根据您的需要进行修改:
Update: To make rule which reacts on any input variable create custom url rule class, here is some example, modify to your needs:
class PageUrlRule extends CBaseUrlRule
{
public function createUrl($manager, $route, $params, $ampersand)
{
// Ignore this rule for creating urls
return false;
}
public function parseUrl($manager, $request, $pathInfo, $rawPathInfo)
{
// Ignore / url or any controller name - which could conflict with username
if($pathInfo == '/')
{
return true;
}
// Search for username or any resource in db
// This is for mongo so it should be tuned to your db,
// just check if username exists
$criteria = new EMongoCriteria();
$criteria->url->$lang = $url;
$criteria->select(['_id']);
$criteria->limit(1);
$model = PageItem::model();
$cursor = $model->findAll($criteria);
// Create route, instead of $url id can be used
$route = sprintf('content/page/view/url/%s', urlencode($url));
// If found return route or false if not found
return $cursor->count() ? $route : false;
}
}
然后将此规则放在 urlmanager 配置的开头
Then place this rule in beginning of urlmanager config
'rules' => [
[
'class' => 'application.modules.content.components.PageUrlRule'
],
// Other rules here
重要:如果用户的用户名与您的控制器相同,它将匹配用户名,控制器将无法访问.您必须禁止注册与控制器同名的用户.
Important: If user has username same as your controller, it will match username and controller will be inaccessible. You must forbid registering users with same names as controllers.
这篇关于YII 框架用户友好 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!