2017-07-10 42 views
0

使用Symfony的2.8事件調度器和容器組件內Symfony的應用的Symfony此事件服務標籤內部沒有Symfony的應用

從我的引導/內核文件:

$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 } 

手動訂閱的作品,但我希望事件自動附加g伊芬從YAML文件中的標籤

+0

你至少需要爲了揭開序幕RegisterListenerPass「編譯」的容器()。從來沒有嘗試過在框架之外使用編譯器,所以不能提供任何細節。 – Cerad

+0

添加了compile()調用,但仍然沒有骰子。我會進一步調查。 –

+1

創建了一個獨立的示例,與我的驗證確實無誤。 (如果您想要參考某些內容):https://github.com/simshaun/so-45003754 – simshaun

回答

1

我創造出瞭如何設置容器,事件調度和RegisterListenersPass獨立回購:

https://github.com/simshaun/so-45003754

Symfony的2.8需要爲RegisterListenersPass起作用的ContainerAwareEventDispatcher

這裏的設置/佈線的肉:

<?php 

use Symfony\Component\Config\FileLocator; 
use Symfony\Component\DependencyInjection\ContainerBuilder; 
use Symfony\Component\DependencyInjection\Definition; 
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; 
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag; 
use Symfony\Component\DependencyInjection\Reference; 
use Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher; 
use Symfony\Component\EventDispatcher\DependencyInjection\RegisterListenersPass; 
use Symfony\Component\EventDispatcher\EventDispatcherInterface; 

require __DIR__.'/vendor/autoload.php'; 


class App 
{ 
    protected $container; 

    public function __construct() 
    { 
     $builder = new ContainerBuilder(new ParameterBag()); 
     $builder->addCompilerPass(new RegisterListenersPass()); 

     $definition = new Definition(ContainerAwareEventDispatcher::class, [new Reference('service_container')]); 
     $builder->setDefinition('event_dispatcher', $definition); 

     $loader = new YamlFileLoader($builder, new FileLocator(__DIR__)); 
     $loader->load('services.yml'); 

     $builder->compile(); 
     $this->container = $builder; 
    } 

    public function getEventDispatcher(): EventDispatcherInterface 
    { 
     return $this->container->get('event_dispatcher'); 
    } 
} 


$app = new App(); 
$ed = $app->getEventDispatcher(); 
$ed->dispatch('my.event');