下面的代碼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
值。我設置了一個breakpoint
在onCreateNewTransaction
方法,我發現這個函數不會被調用。
修訂
問題解決了
`onCreateNewTransaction」應該是公開的,而不是私人
我可能會錯過一些東西,但爲什麼在這種情況下需要事件? 在構造函數中分配這些屬性會更有意義嗎? 除此之外,您應該注入EventDispatcher而不是在構造函數中實例化它,這樣您就可以創建固定的依賴關係。 –