0

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

我想要的是让这个网址:

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

指向:

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

foo指向哪里12

而且,由于我使用的是“路径”urlFormat,并且正在使用其他 url 规则来隐藏indexand id=,所以上面的 URL 最终应该指向:

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

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

4

1 回答 1

0

您的操作应该接受一个参数$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'),
于 2014-10-10T15:34:53.580 回答