4

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?

Haru Atari
  • 1,502
  • 2
  • 17
  • 30
DGT
  • 391
  • 1
  • 3
  • 13

3 Answers3

3

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.

Haru Atari
  • 1,502
  • 2
  • 17
  • 30
  • All the Rest Api implementation is in a separate module. I wanted a way to invoke a rest call for some controller action. Is that a bad design? What should i do to make it right – DGT Oct 12 '15 at 06:02
1

Try to use this.

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

Does the job

Phemelo Khetho
  • 231
  • 1
  • 4
  • 14
0

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

Zack
  • 1,527
  • 2
  • 20
  • 32