2016-09-27 33 views
0

下面的代码Symfony的用户此事件不运作

use Application\Events\TransactionCreatedEvent; 
use Symfony\Component\EventDispatcher\EventSubscriberInterface; 
use Symfony\Component\EventDispatcher\EventDispatcher; 

class Transaction implements EventSubscriberInterface 
{ 
    protected $date; 
    protected $name; 
    protected $address; 
    protected $phone; 
    protected $price_with_vat; 
    protected $transaction_type; 
    protected $receipt; 
    protected $currency; 


    protected function __construct($date, $name, $address, $phone, $price_with_vat, $transaction_type, $receipt, $currency) 
    { 
     $dispatcher = new EventDispatcher(); 
     $dispatcher->addSubscriber($this); 
     $dispatcher->dispatch(TransactionCreatedEvent::NAME, new TransactionCreatedEvent($date, $name, $address, $phone, $price_with_vat, $transaction_type, $receipt, $currency)); 
    } 

    public static function CreateNewTransaction($date, $name, $address, $phone, $price_with_vat, $transaction_type, $receipt, $currency){ 
     return new Transaction($date, $name, $address, $phone, $price_with_vat, $transaction_type, $receipt, $currency); 
    } 

    private function onCreateNewTransaction($Event){ 
     $this->date = $Event->date; 
     $this->name = $Event->name; 
     $this->address = $Event->address; 
     $this->phone = $Event->phone; 
     $this->price_with_vat = $Event->price_with_vat; 
     $this->transaction_type = $Event->transaction_type; 
     $this->receipt = $Event->receipt; 
     $this->currency = $Event->currency; 
    } 

    public static function getSubscribedEvents() 
    { 
     return array(TransactionCreatedEvent::NAME => 'onCreateNewTransaction'); 
    } 
} 

它想派遣TransactionCreated事件并获得由类本身和onCreatedNewTransaction功能,以设置类的属性得到调用捕获。

Transaction类实例化像

$Transaction = Transaction::CreateNewTransaction('6/6/2016', 'John'....); 

但是当我调试项目的$Transaction对象有null值。我设置了一个breakpointonCreateNewTransaction方法,我发现这个函数不会被调用。

修订

问题解决了

`onCreateNewTransaction”应该是公开的,而不是私人

+0

我可能会错过一些东西,但为什么在这种情况下需要事件? 在构造函数中分配这些属性会更有意义吗? 除此之外,您应该注入EventDispatcher而不是在构造函数中实例化它,这样您就可以创建固定的依赖关系。 –

回答

2

你的方法CreateNewTransaction是静态的,所以创建并没有Transaction实例因此__constructor是永远调用。

这是关于为什么此代码不起作用。

但是,除此之外,我必须说这是Symfony系统的一个完全误用系统Event。使用框架(没有EventDispatcher组件),您不能自己创建EventDispatcher。它是由FrameworkBundle创建的,你应该只注入event_dispatcher服务到你需要的任何东西。否则,你可能会在不同的范围内(每个调度员都有它自己的订户和它自己的事件)很快地迷路,而且这是浪费资源。

+0

关于您的第一个问题,我的调试会话证明相反。受保护的__constructor被调用并注入了所有适当的数据。关于你的第二个担心,我在我的组合根目录(又名bootstrap)上实例化一个'EventDiaspatcer'并注入它所需的位置。这个“新”构造函数仅用于清晰的目的。 – dios231

+0

无论如何,当你创建像这样的事务'$ Transaction = Transaction :: CreateNewTransaction('6/6/2016','John'....);'没有人用你的静态方法触发这个事件。而当你创建一个实例'Transaction'时,正在创建一个新的事务,但是它的值为空值 - 你在调试器中看到的 –

+0

只是想指出有时候创建你自己的事件调度器是合法的。它实际上可以帮助将听众与其他框架监听器隔离开来。所以不要完全排除。 – Cerad