I'm wondering if it's possible in Yii2 to call a function automatically when executing php init
command?
I have a component/extension which has a function that I want to call only when the Yii2 app is initialized. Can this function be registered in anywhere so that it will be automatically called and is it even possible?
init (Yii Application Initialization Tool) is available for Advanced Application Template only and written in procedural style (not OOP).
Unfortunately, init
does not raise any events, so you can't add any event handlers to execute custom code.
The easiest way to solve the problem is to modify init
file itself, but it's not good practice, because changes can be lost on framework update (file is included in git trackable files in framework core).
My advice will be create separate console command for handling that and execute it right after php init
:
php init your-custom-console-controller/action-name
If you are using deploy tools, such as Deployer, you can easily add your custom command for execution right after init.
Recipe for Yii2 Advanced Application Template exists, so you can add your custom command like so:
task('deploy:your_custom_command', function () {
cd('{{release_path}}');
run('php yii your-custom-console-controller/action-name');
});
after('deploy:init', 'deploy:your_custom_command');
Then you just run:
dep deploy production
And forget about everything what you need to do to deploy your project.
Definetely recommend to spend some time and learn it, it's worth it.