下面的代码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而不是在构造函数中实例化它,这样您就可以创建固定的依赖关系。 –