【发布时间】:2016-09-27 09:42:10
【问题描述】:
以下代码
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 值。我在onCreateNewTransaction 方法上设置了一个breakpoint,我发现因此函数没有被调用。
更新
问题解决了
`onCreateNewTransaction' 应该是公开的而不是私有的
【问题讨论】:
-
我可能遗漏了一些东西,但为什么在这种情况下需要事件?在构造函数中分配这些属性不是更有意义吗?除此之外,您应该注入 EventDispatcher 而不是在构造函数中实例化它,这样您就可以创建固定的依赖关系。
标签: php symfony mediator event-dispatching