以下代码
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'应该是公开的而不是私人的
答案 0 :(得分:2)
您的方法CreateNewTransaction
是静态的,因此不会创建Transaction
的实例,因此永远不会调用__constructor
。
这就是为什么这段代码无效。
但是,除此之外,我必须说它完全滥用了Event
Symfony系统。使用框架(无EventDispatcher
组件),您不能自己创建EventDispatcher。它是由FrameworkBundle创建的,您应该只将event_dispatcher
服务注入到您需要的任何内容中。
否则,您可能会在不同的范围内(每个调度员拥有自己的订阅者和它自己的事件)很快迷失方向,而且,'是浪费资源。