简体   繁体   中英

How can I write a beforeAction() that applies to all controllers?

I want to register a script within the beforeAction method(Yii Framework). But I don't want to repeat that method in every single controller, so my question is how can i create a beforeAction() that all controllers will inherit?

Thx,

The default yiic generated yii webapp has a Controller class in project/protected/components/Controller.php , and all controllers in the app inherit from this Controller.

That class is the perfect place to add the beforeAction .

Edit: Incase you have not used yiic and don't have this default Controller class, it's fine to add a new class that extends from CController, and then have your controllers extend from this new class. You can keep all the common functionality for your controllers in this parent controller class.

You need to create BaseController.php inside components directory. Inside this file you will inherit your BaseController from CController. Write your beforeAction there. After this you will need to inherit all you controllers from BaseController.

1) Create Common parent Controller with extended with CController (example SomeController)

2) register script in the beforeAction() in this Controller (example SomeController)

3) extend this controller of your SiteController or Module Controller.

<?php

class SomeController extends CController
{
    public function beforeAction()
    {
        // Your Register Script
    }
}


class SiteController extends SomeController
{
    // public function actionIndex
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM