网址规则:
array(
'<username:\w+>'=>'user/view',
)
请注意,在这种方案中,您还必须为所有控制器创建规则并将上述规则放在最后,因此最好在其前面加上 user:
array(
'user/<username:\w+>'=>'user/view',
)
结果网址将是example.com/user/username
在行动:
public function actionView($username) ...
更新:
要使对任何输入变量做出反应的规则创建自定义 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
重要提示:如果用户的用户名与您的控制器相同,它将匹配用户名并且控制器将无法访问。您必须禁止注册与控制器同名的用户。