php - Yii 将所有操作路由到 Controller 中的一种方法

标签 php routes yii

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

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

我想做的是让所有内容都进入ArticleController.php中的方法actionIndex(),并让该方法确定如何处理该操作。所以我的问题是如何将所有操作路由到 Yii Controller 中的一个方法?

最佳答案

就您而言,我认为最好使用 filterbeforeAction 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/

相关文章:

php - Yii createCommand() 以不同的数组格式返回数据集

php - 无法连接到 smtp(连接被拒绝)

docker - 使用 ocelot 和 docker 服务使用路由 ApiGateway 时出错

php - 是否可以传递一个计数值到 CListView 中查看并更新到 YII 中 itemView 的每次调用

asp.net-mvc - ASP.NET MVC 路由测试被认为是单元测试还是集成测试?

java - 在 Akka 中实现基于内容的路由器模式

yii - 在 Controller 中设置 const 并在 yii 中作为下拉列表调用 View

php - 在 symfony2 中限制每秒 swiftmailer 电子邮件

PHP : Compare and display if value equal

php - PDO 两表连接