Yii将所有操作路由到控制器中的一个方法



我正在尝试使用Yii制作一个类似cms的应用程序。功能将类似于:

http://www.example.com/article/some-article-name

我想做的是让一切都按照ArticleController.php中的方法actionIndex()进行,并让这一方法决定如何处理操作。所以我的问题是如何将所有操作路由到Yii中控制器中的一个方法?

在您的情况下,我认为最好使用过滤器或beforeAction方法。


过滤方式:

Filter是一段代码,配置为在控制器操作执行之前和/或之后执行。

示例:

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方式:

此方法在执行操作之前立即调用(在所有可能的筛选器之后)。您可以重写此方法以在最后一刻为操作做准备。

示例:

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 ...
}

作为旁注,您也可以通过以下方式访问控制器内的当前操作:$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 
}

将其添加到配置中urlManager规则的开头:

'article/*' => 'article',

您的规则必须类似于以下内容:-

'rules' => array(
'<controller:w+>/<action:w+>' => '<controller>/<action>',
'<controller:w+>/<action:w+>' => 'article/index',
),

如果控制器和/或操作不存在,这将把所有请求传递给ArticleControllerPHP类中的actionIndex函数。

我猜你只是想在"视图"文件夹中放入一堆静态页面,然后自动选择并渲染它们,而无需在控制器中为每个页面添加操作。

上面建议的过滤器()和beforeAction(),甚至__construct()都不起作用(如果操作不存在,过滤器和beforeAction根本不会启动,__construction非常混乱,因为如果你把你的功能放在__constructure中,Yii甚至不知道它应该调用哪个控制器/操作/视图)

但是,有一个简单的解决方法,涉及URL管理器

在您的配置中,在URL管理器的规则中,添加以下行之一(取决于您的路径设置)

'articles/<action:w+>' => 'articles/index/action/<action>',

'articles/<action:w+>' => 'articles/index?action=<action>',

然后,在你的文章中,控制器只需张贴这个(或类似的)索引动作

public function actionIndex() {
$name = Yii::app()->request->getParam('action');
$this->render($name);
}

然后你可以调用像/article/myarticle或/article/yourarticle这样的页面,而无需在控制器中设置任何函数。您所需要做的就是在views/articles文件夹中添加一个名为myarticle.php或yourarticle.php的文件,并在这些文件中键入html内容。

最新更新