2016-09-27 31 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