Call the controller in another module from another controller

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

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

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

Sort of:

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

Is it possible?

+4
source share
3 answers

Yes you can do it. But this points to problems in your architecture. This is bad practice when the controller contains complex logic.

Maybe you can move the general part of the code into the model and call it in the controllers as a method? Or name $this->redirect()instead Yii::$app->runAction()? Try to avoid tight coupling between modules.

:
, . . :

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");
    }
}

:

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();     
    }
}

MyModel::generateResult() , . runAction().

, runAction() . .

+3

.

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

+1

runAction() .

0

Source: https://habr.com/ru/post/1610695/


All Articles