Call a controller in another module from another controller

4.9k views Asked by At

Yii::$app->runAction('new_controller/new_action', $params);

I believe this can be used to call a controller action from another controller.

Is there a way to call a controller action that resides in another module?

Something like:

Yii::$app->runAction('/route/to/other/module/new_controller/new_action', $params);

Is this possible?

3

There are 3 answers

0
Zack On

Its possible with the function runAction() in Module. Check the documentation here

1
Haru Atari On

Yes you can do that. But it indicates of problems in your architecture. It's bad practice when controller contains complex logic.

May be you can move common part of the code into model and call him in controllers as method? Or call $this->redirect() instead Yii::$app->runAction()? Try to avoid strong connectivity of modules.

update:
For example this sample code is not very good. Because you can not write unit tests for logic in actions without initialization of request. It is very simple example:

class SampleController extends Controller {
    public function actionMyAction() {
        // do thomething
        return $result;        
    }
}

class SampleRestController extends Controller {
    public function actionMyRestAction() {
        return \Yii::$app()->runAction("sample/my-action");
    }
}

But you can do this:

class MyModel { // 
    public function generateResult() {
        // do thomething
        return $result;
    }
}

class SampleController extends Controller {
    public function actionMyAction() {
        return (new MyModel)->generateResult();       
    }
}

class SampleRestController extends Controller {
    public function actionMyRestAction() {
        return (new MyModel)->generateResult();     
    }
}

Here you can call MyModel::generateResult() in different actions and you can write unit-tests for this method easily. And you can do this without calling of runAction().

I do not say that runAction() is bad. But using of this method is occasion to reflect.

0
Phemelo Khetho On

Try to use this.

Yii::$app->runAction('checksheet/index', ['param1' => $param1, 'param2' => $param2]);

Does the job