php – 如何在Yii或slug麻烦中使用beforeAction
Yii开发jedis!
我正在研究一些旧的Yii项目,必须向他们添加一些功能. Yii是非常合乎逻辑的框架,但它有一些我无法理解的东西.也许我还没理解Yii-way.所以我将逐步描述我的问题.对于不耐烦的人 – 最后简要提问. 简介:我想在我的项目中添加人类可读的URL. 第1步:首先,我在config / main.php中更新了重写规则: '<controller:w+>/<id:S+>' => '<controller>/view', 我在文章表中添加了新的texturl列.因此,我们将在这里存储人类可读的新文章的部分内容.然后我用texturl更新了一篇文章进行测试. 第2步:应用程序在ArticleController的actionView中显示文章,所以我在那里添加了这个用于预处理ID参数的代码: if (is_numeric($id)) { // User try to get /article/359 $model = $this->loadModel($id); // Article::model()->findByPk($id); if ($model->text_url !== null) { // If article with ID=359 have text url -> redirect to /article/text-url $this->redirect(array('view','id' => $model->text_url),true,301); } } else { // User try to get /article/text-url $model = Article::model()->findByAttributes(array('text_url' => $id)); $id = ($model !== null) ? $model->id : null ; } 然后开始遗留代码: $model = $this->loadModel($id); // Load article by numeric ID // etc 它完美无缺!但… 第3步:但我们有许多ID参数的动作!我们要做什么?使用该代码更新所有操作?我认为这很难看.我找到了CController::beforeAction方法.看起来不错!所以我声明beforeAction并在那里放置ID preproccess: protected function beforeAction($action) { $actionToRun = $action->getId(); $id = Yii::app()->getRequest()->getQuery('id'); if (is_numeric($id)) { $model = $this->loadModel($id); if ($model->text_url !== null) { $this->redirect(array('view',301); } } else { $model = Article::model()->findByAttributes(array('text_url' => $id)); $id = ($model !== null) ? $model->id : null ; } return parent::beforeAction($action->runWithParams(array('id' => $id))); } 是的,它适用于两种URL格式,但它执行actionView TWICE并显示两次页面!我该怎么办?我完全糊涂了.我有没有选择正确的方法来解决我的问题? 简而言之:我可以在执行任何操作之前执行ID(GET参数),然后使用仅修改的ID参数运行请求的操作(一次!)?
最后一行应该是:
return parent::beforeAction($action); 还问你我没有得到你的步骤:3. 如你所说,你有很多控制器,你不需要在每个文件中编写代码,所以你使用的是beforeAction: $model = Article::model()->findByAttributes(array('text_url' => $id)); =====更新回答====== 我已更改此功能,请立即查看. 如果$id不是nummeric,那么我们将使用model找到它的id并设置$_GET [‘id’],因此在进一步的控制器中它将使用该numberic id. protected function beforeAction($action) { $id = Yii::app()->getRequest()->getQuery('id'); if(!is_numeric($id)) // $id = how-to-make-pretty-urls { $model = Article::model()->findByAttributes(array('text_url' => $id)); $_GET['id'] = $model->id ; } return parent::beforeAction($action); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |