Php YII框架用户友好URL
我的yii PHP项目有UserController,它有一个名为actionView的操作。我可以使用以下URL访问用户查看页面Php YII框架用户友好URL,php,yii,Php,Yii,我的yii PHP项目有UserController,它有一个名为actionView的操作。我可以使用以下URL访问用户查看页面 mysite.com/user/view/id/1 我想把那个换成 mysite.com/username 我该怎么做呢 我知道,我可以简单地创建规则,以便更方便地获取url,例如 mysite.com/user/username 但将数据库资源名称作为直接参数(mysite.com/username)的url方案则完全不同。url规则: array(
mysite.com/user/view/id/1
我想把那个换成
mysite.com/username
我该怎么做呢
我知道,我可以简单地创建规则,以便更方便地获取url,例如
mysite.com/user/username
但将数据库资源名称作为直接参数(mysite.com/username
)的url方案则完全不同。url规则:
array(
'<username:\w+>'=>'user/view',
)
更新:
要创建对任何输入变量作出反应的规则,请创建自定义url规则类,下面是一些示例,请根据您的需要进行修改:
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配置的开头
'rules' => [
[
'class' => 'application.modules.content.components.PageUrlRule'
],
// Other rules here
重要信息:如果用户的用户名与您的控制器相同,它将匹配用户名,控制器将无法访问。您必须禁止注册与控制器同名的用户。“2.用户友好url”虽然看起来像是重复的,但仅将参数用作url的情况有点不同。
example.com/User/username
不是我要查找的内容。我想删除用户部分。我想要example.com/username
。最好创建custo url规则类,我稍后会发布它,我在某处有类似的东西
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;
}
}
'rules' => [
[
'class' => 'application.modules.content.components.PageUrlRule'
],
// Other rules here