在 Symfony 应用程序中使用Symfony 2.8 Event Dispatcher 和 Container 组件
从我的引导程序/内核文件中:
$this->container = new ContainerBuilder(new ParameterBag());
$this->getContainer()->addCompilerPass(new RegisterListenersPass());
$this->getContainer()->register('event_dispatcher', EventDispatcher::class);
$this->loadServiceConfig(); // See below for reference
/** @var EventDispatcher $ed */
$ed = $this->getContainer()->get('event_dispatcher');
// The next line works
$ed->addSubscriber(new SampleSubscriber());
...
private function loadServiceConfig()
{
$loader = new YamlFileLoader($this->container, new FileLocator(__DIR__);
$loader->load('config/services.yml');
}
来自config/services.yml
:
services:
sample_subscriber:
class: Sample\Event\SampleSubscriber
public: true
tags:
- { name: kernel.event_subscriber }
手动订阅有效,但我希望事件能够自动附加给定 yaml 文件中的标签