dnoegel / lazy-subscriber
允许您将匿名函数定义为Shopware(4.2.0+)的事件监听回调
dev-master
2015-10-10 19:45 UTC
This package is auto-updated.
Last update: 2024-09-04 15:13:02 UTC
README
Shopware的SubscriberInterface
允许您定义订阅者,以便轻松订阅Shopware事件。然而,SubscriberInterface
不支持匿名函数作为回调,主要是因为Shopware试图与Symfony EventDispatcher
保持向前兼容。
LazySubscriber
将为您提供一种简单的方法来将回调定义为匿名函数,如果您想为Shopware的DIC注册大量服务,这将特别方便。使用LazySubscriber
,您可以像在Pimple中一样定义您的服务。
如何使用
安装
如果您想使用composer安装此依赖项,只需运行composer require dnoegel/lazy-subscriber
。
订阅者
namespace YourPlugin\Subscriber; class ContainerSubscriber extends LazySubscriber { public function define() { return [ 'my_plugin.cart' => function() { return new Cart(); }, 'my_plugin.persister' => function(DIC $c) { return new Persister($c->get('connection')); } ]; } }
引导
为了使用您定义的上述订阅者,您需要在运行时注册它。
class Shopware_Plugins_Frontend_YourPlugin_Bootstrap extends Shopware_Components_Plugin_Bootstrap { // register namespaces for your plugin as well as for the lazy-subscriber library public function registerMyComponents() { $this->Application()->Loader()->registerNamespace( 'Shopware\YourPlugin', $this->Path() ); // you can use this require_once __DIR__ . '/vendor/autoload.php'; // or this line to include the dependency: $this->Application()->Loader()->registerNamespace( 'Dnoegel\LazySubscriber', $this->Path() . '/vendor/dnoegel/lazy-subscriber/src' ); } // install: register an early event public function install() { $this->subscribeEvent( 'Enlight_Controller_Front_DispatchLoopStartup', 'onStartDispatch' ); return true; } // Dynamically add your own subscriber public function onStartDispatch(Enlight_Event_EventArgs $args) { $this->registerMyComponents(); $subscribers = array( new \Shopware\YourPlugin\Subscriber\ContainerSubscriber(Shopware()->Container()) ); foreach ($subscribers as $subscriber) { $this->Application()->Events()->addSubscriber($subscriber); } } }
我应该使用它吗?
对于在插件中填充DI,这可能还不错,因为这在开发期间有些繁琐。您不应该使用它作为默认事件,也不应该将其用作将所有事件订阅者定义在一个大型的懒订阅者中的方式。此外,请注意,如果了解幕后发生的事情以及需要注意什么,事件订阅者可以很好地工作。如果不是这种情况,您可能暂时坚持使用“默认事件注册”方式。