Run another controller's action with parameters

Hello.

I want to run a specific controller’s action after login and logout.

I use Yii::$app->runAction(‘controller/action’, [‘logout’=>1] ); but the parameter is not passed at the $_GET array.

Am I missing something?

How can I run a specific action from another controller?

Thanks a lot.

Typically: you don’t.

If a piece of code needs to be executed in multiple controller actions it should be factored out and moved into a new class. Depending on the actual logic this new class can be an action filter/controller behavior, an application component or a simple static helper. This way you can avoid unnecessary coupling between controllers and don’t have to (ab)use the framework’s routing mechanism for a simple method call.

And probably you can simply redirect the browser to the desired page after login or logout.

i need to do this once, but in the same controller, and put the parameters in the $_POST array directly




$_POST['message'] = $message; 

return $this->actionView([(get parameters));

so, in other controller ($this is a controller caller) maybe something like this:


$controller = new ControllerClass([$controllerId, $this->module]);

$_POST['message'] = $message; 

return $controller->actionSomeAction([(get parameters)];

it worked for me :D

i think sometimes, is necessary, call actions from one controller to another, and it is the latter that is responsible for the response.

for exanple:

if after an action in the controller ‘a’ where I get a model car in the $ _GET and after certain operations want to show the view of the car it would make sense to call from the controller ‘a’ to CarController->actionView() to show the car

It would be slower than just make the call to action function of another controller?

Thank you all for your answers. I used another approach to tackle this issue.

First, I created an Utils Class in Assets folder:




namespace backend\assets;

use Yii;


class Utils

{

     public function myFunction($param1, $param2) 

     {

         // do calculations

     }

}



Then I instantiated the Utils Class to execute the desired function.




public function actionLogout()

{

     $utils = new \backend\assets\Utils;

     $utils->myFunction('007', 1);

     Yii::$app->user->logout();


     return $this->goHome();

}



It might be. I was thinking about a simple sequence in which redirecting can do the job.

And I second @phtamas’s recommendation: