我正在尝试使用 Yii 制作一个类似 cms 的应用程序。该功能将类似于:
http://www.example.com/article/some-article-name
我想做的是让所有内容都进入ArticleController.php
中的方法actionIndex()
,并让该方法确定如何处理该操作。所以我的问题是如何将所有操作路由到 Yii Controller 中的一个方法?
最佳答案
就您而言,我认为最好使用 filter或 beforeAction
method .
过滤方式:
Filter is a piece of code that is configured to be executed before and/or after a controller action executes.
示例:
class SomeController extends Controller {
// ... other code ...
public function filters() {
return array(
// .. other filters ...
'mysimple', // our filter will be applied to all actions in this controller
// ... other filters ...
);
}
public function filterMysimple($filterChain) { // this is the filter code
// ... do stuff ...
$filterChain->run(); // this bit is important to let the action run
}
// ... other code ...
}
beforeAction
方式:
This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.
示例:
class SomeController extends Controller {
// ... other code ...
protected function beforeAction($action) {
if (parent::beforeAction($action)){
// do stuff
return true; // this line is important to let the action continue
}
return false;
}
// ... other code ...
}
顺便说一句,您也可以通过以下方式访问 Controller 中的当前操作: $this->action
,以获取 id
的值:$this->action->id
:
if($this->action->id == 'view') { // say you want to detect actionView
$this->layout = 'path/to/layout'; // say you want to set a different layout for actionView
}
关于php - Yii 将所有操作路由到 Controller 中的一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13904085/