Yii 路由器规则将关键字重定向到操作的 $_GET 参数



在Yii中,是否可以使用路由器规则将URL中的关键字"翻译"为某个操作的$_GET参数?

我想要的,是让这个网址:

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

指向:

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

其中CCD_ 3指向CCD_。

而且,由于我使用"path"urlFormat,并且使用其他url规则来隐藏indexid=,因此上面的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',

还有一件事需要注意,如果你走这条路,请确保slug在你的数据库中是唯一的,你还应该在模型中强制执行验证规则:

    array('slug', 'unique'),

最新更新