0

以下代码

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值。我设置了一个breakpointatonCreateNewTransaction方法,我发现因此函数没有被调用。

更新

问题解决了

`onCreateNewTransaction' 应该是公开的而不是私有的

4

1 回答 1

2

您的方法CreateNewTransaction是静态的,因此不会Transaction创建任何实例,因此 __constructor永远不会被调用。

这是关于为什么此代码不起作用。

Event但是,除此之外,我必须说这是对 Symfony 系统的完全滥用。使用框架(无EventDispatcher组件),您不能自己创建 EventDispatcher。它是由 FrameworkBundle 创建的,你应该只将event_dispatcher服务注入你需要的任何东西。

否则,您可能会很快迷失在不同的范围内(每个调度程序都有自己的订阅者和自己的事件),此外,这是一种资源浪费。

于 2016-09-27T10:52:07.240 回答