Attach Method To Controller

Hi,

I have a Controller but it has a huge code

So according to few conditions I want to attach some method from another files.

I know I could make some Controller extends the main one but the above task should be inside to the action.

What is the best way to do that ?

Many thanks

Hello

Do you mean like this?


class SomeController extends Controller

{

    …


    public function yourMethod($arg1, $arg2 = null)

    {

        …

    }

}


…


//and for instance, somewhere in your view

$this->yourMethod($model, 'value')

EDIT: or do you mean incorporating actions for other controllers, or the main controller?

Hi bennouna

I mean like this


class SomeController extends Controller

{

    …

    public function beforeAction($action)

    {

       if  ($action=='MyMethod2') <"attach from SomeMethodsClass">

    }


    public function actionMyMethod1()

    {

        …

    }


    public function actionMyMethod2()

    {

        $this->myMethod3();

    }

}







class SomeMethodsClass //extends Controller

{

    …


    public function myMethod3()

    {

        $this->render('index');

    }


    public function myMethod4()

    {

         $this->render('index2');

    }

}




I think you could solve this using behaviors.




class SomeController extends Controller

{

    public function beforeAction($action)

    {

        switch ($action->id)

        {

        case 'MyMethod2':

            $this->attach( 'someMethods', array(

                'class' => 'app.behaviors.SomeMethodsBehavior',

                // more initialization if needed

            ));

            break;

        }


        return parent::beforeAction($action);

    }


    public function actionMyMethod1()

    {

        …

    }


    public function actionMyMethod2()

    {

        // myMethod3 defined in "app.behaviors.SomeMethodsBehavior"

        $this->myMethod3();

    }

}



I remember a state machine extension that does dynamic behavior attachment and detachment depending on state transitions. It might be possible to re-use this extension if you look at an controller as an state machine like this:




entryPoint --> actionExecution_1 --> exitPoint

           \                      /

            -> actionExecution_2 -



Thanks Ben

In my case it works using attachBehavior instead attach. for example


class myBehavior extends CBehavior {

    public function extFunction(){

        return ...;

    } 

}

and in Controller


$this->attachBehavior('myextraMethod1', array(

            'class' => 'application.components.myBehavior',

        ));


...

$this->extFunction();



did you read this: http://www.yiiframework.com/wiki/170/actions-code-reuse-with-caction/ ?

Hi redguy

Excellent wiki

In my case there is a little difference.

The attaching take place on the fly and in another controller/component, so the above wiki is useful for another issue.

Thanks for response