将关键字重定向到操作的Yii路由器规则';s$\u获得参数化

将关键字重定向到操作的Yii路由器规则';s$\u获得参数化,yii,yii-url-manager,yii-routing,Yii,Yii Url Manager,Yii Routing,在Yii中,是否可以使用路由器规则将URL中的关键字“翻译”为某个操作的$\u GET参数 我想要的是让这个URL: http://example.com/MyModule/MyController/index/foo 指: http://example.com?r=MyModule/MyController/index&id=12 其中foo指向12 而且,由于我正在使用“路径”url格式,并且正在使用其他url规则隐藏索引和id=,因此上面的url最终应该指向: http://example

在Yii中,是否可以使用路由器规则将URL中的关键字“翻译”为某个操作的$\u GET参数

我想要的是让这个URL:

http://example.com/MyModule/MyController/index/foo

指:

http://example.com?r=MyModule/MyController/index&id=12

其中
foo
指向
12

而且,由于我正在使用“路径”url格式,并且正在使用其他url规则隐藏
索引
id=
,因此上面的url最终应该指向:

http://example.com/MyModule/MyController/12


可以通过在urlManager组件的配置文件中设置规则来实现这一点吗?

您的操作应该接受一个参数
$id

public function actionView($id) {
    $model = $this->loadModel($id);
您需要做的是在同一控制器中修改loadModel函数:

/**
 * @param integer or string the ID or slug of the model to be loaded
 */
public function loadModel($id) {

    if(is_numeric($id)) {
        $model = Page::model()->findByPk($id);
    } else {
        $model = Page::model()->find('slug=:slug', array(':slug' => $id));
    }

    if($model === null)
        throw new CHttpException(404, 'The requested page does not exist.');

    if($model->hasAttribute('isDeleted') && $model->isDeleted)
        throw new CHttpException(404, 'The requested page has been deleted for reasons of moderation.');

    // Not published, do not display
    if($model->hasAttribute('isPublished') && !$model->isPublished)
        throw new CHttpException(404, 'The requested page is not published.');

    return $model;
}
然后,您需要修改urlManager规则以接受字符串,而不仅仅是ID:

删除以下默认规则中的
:\d+

'<controller:\w+>/<id:\d+>' => '<controller>/view',
'<controller:\w+>/<id>' => '<controller>/view',
    array('slug', 'unique'),