Home > Enterprise >  execute global function automatically on running controller in yii2
execute global function automatically on running controller in yii2

Time:11-21

We have web pages, where user will be redirected to $this->goHome(), if the session timeouts or user logouts. We have to destroy the all the session so, we have to add a function with destroying session. This function should be executed before running any action/controller in Yii2 i.e. similar to hooks in codeigniter. We have tried a helper function with destroying session and we have called the function as HomeHelper::getHelpDocUrlForCurrentPage(); in main.php layout, but the layout will be executed after running action in controller, it should work on running any controller as we have 100 controllers. How this can be achieved, please suggest us in right way. Thanks in advance.

CodePudding user response:

in

config/main.php 

you could try using 'on beforeAction'

return [
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'bootstrap' => [
        'log',
        ....     
    ],   
    'on beforeAction' => function($event){
        // your code ..
    } ,
    'modules' => [
       ....
    ],
    ...
];

CodePudding user response:

While @ScaisEdge solution would work I believe application config is not proper place to hold application logic.

You should use filters to achieve result you want.

First you need to implement filter with your logic. For example like this:

namespace app\components\filters;

class MyFilter extends yii\base\ActionFilter
{
    public function beforeAction() {
        // ... your logic ...
    
        // beforeAction method should return bool value.
        // If returned value is false the action is not run
        return true;
    }
}

Then you want to attach this filter as any other behavior to any controller you want to apply this filter on. Or you can attach the filter to application if you want to apply it for each action/controller. You can do that in application config:

return [
    'as myFilter1' => \app\components\filters\MyFilter::class,
    // ... other configurations ...
];

You might also take a look at existing core filters if some of them can help you.

  • Related