【问题标题】:YII framework user friendly URLYII 框架用户友好的 URL
【发布时间】:2013-09-26 10:24:15
【问题描述】:

我的 yii PHP 项目有 UserController 并且它有一个名为 actionView 的动作。我可以使用以下 URL 访问用户视图页面

mysite.com/user/view/id/1

我想把那个改成

mysite.com/username

我该怎么做。

我知道我可以简单地创建规则以更加用户友好地获取诸如

之类的 url
mysite.com/user/username

但是将数据库资源名称作为直接参数 (mysite.com/username) 的 url 方案则完全不同。

【问题讨论】:

标签: php yii


【解决方案1】:

网址规则:

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

重要:如果用户的用户名与您的控制器相同,它将匹配用户名并且控制器将无法访问。您必须禁止注册与控制器同名的用户。

【讨论】:

  • example.com/user/username 不是我要找的东西。我想删除用户部分。我要example.com/username
  • 最好创建custo url规则类,我稍后再贴,我在某处有类似的东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-05
  • 2010-11-14
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多