How to make extension to perform custom initialization on a Magento 2 start
There are at least two use cases in this situation. In Magento 2 you can custom mini-libraries with such short popular global functions as rm_customer_logged_in():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<type name='\Magento\Framework\AppInterface'> <plugin name='Df\Framework\AppInterfacePlugin' type='Df\Framework\AppInterfacePlugin' sortOrder='100' /> </type> <?php namespace Df\Framework; use \Magento\Framework\AppInterface; class AppInterfacePlugin { /** * @see \Magento\Framework\AppInterface::launch() * @param AppInterface $subject * @return array */ public function beforeLaunch(AppInterface $subject) { // Place your custom initialization code here. return []; } } |
Unfortunately, such approach does not work for console apps. Therefore, for applications like setup:upgrade, use event handlers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<event name='store_collection_load_before'> <observer name='Df\Core\Boot' instance='Df\Core\Boot' method='storeCollectionLoadBefore' /> </event> <?php namespace Df\Core; use \Magento\Framework\Event\Invoker\InvokerDefault; use \Magento\Framework\Event\Observer as _O; class Boot { /** * @used-by InvokerDefault::_callObserverMethod() * @param _O $o * @return void */ public function storeCollectionLoadBefore(_O $o) { if (!self::$_done && 'cli' === PHP_SAPI) { self::run(); } } // other code here... } |
More tips from The Magento 2 Developer’s Cookbook