Code reuse @ init(), Yii bug ??

Hi,

As i see in this page:

http://www.yiiframework.com/doc/guide/1.1/en/basics.controller

I can make a common class file for reuse the code like this:


class PostController extends CController

{

    public function actions()

    {

        return array(

            'edit'=>'application.controllers.post.UpdateAction',

        );

    }

}

and then, the file UpdateAction.php:


class UpdateAction extends CAction

{

    public function run()

    {

        // place the action logic here

    }

}

By this trick the UpdateAction() will be accessible to all controllers that return the actions() array above.

But in my case, it doesn’t work because i would like to use the trick as following:




class myController extends Controller {

public function init() {

        $this->actionCommon();

        parent::init();

    }

public function actions()

    {

        return array(

            'common'=>'application.controllers.common',

        );

    }

....



And (common.php):


class Common extends CAction

{

    public function run()

    {

        $this->reUsedCode();

    }

    public function reUsedCode() {

        ...........

}

}

But i get something like :

myController and its behaviors do not have a method or closure named "common"

Is it a bug from Yii ?

Not at all, of course. :)

A class based action is not a kind of common utility function that you can call inside your controller methods.

If you want to do some common tasks before all controllers’ actions, you can do it in your parent controller, i.e., in your Controller::init().

I plan to never modify the Yii code.

What do you suggest for accessing some methods in many controllers @ init() without code duplicate ?

Is your "commonAction" a real action (in MVC pattern) ? I mean, are you planning to call it via a route ?

If yes, I don’t see why you need to call it in init phase of Controller.

If no, You just need to put this code in a method of your base controller, call it in init method, and make all concerned controllers inherit from this base controller

/protected/Components/Controller.php is not a Yii core, but a part of your application. :)

This is what i did, it works ;)