php - execute global function automatically on running controller in yii2

Solution:

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' => [
       ....
    ],
    ...
];

Answer

Solution:

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.

Source