The following code
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');
}
}
it suppose to dispatch a TransactionCreated
event and get caught by the class itself and the onCreatedNewTransaction
function get invoke in order to set the properties of the class.
The Transaction
class instantiated like
$Transaction = Transaction::CreateNewTransaction('6/6/2016', 'John'....);
but when i debug the project the $Transaction
object have null
values. I set a breakpoint
at onCreateNewTransaction
method and I found that thus function does not get invoked.
UPDATED
Problem solved
`onCreateNewTransaction' should be public instead of private
Your method CreateNewTransaction
is static, so no instances of Transaction
is created and therefore __constructor
is never called.
This is regarding why this code doesn't work.
But, besides, I must say it's a total misuse of Event
system of Symfony. Using framework (no EventDispatcher
component), you must not create EventDispatcher yourself. It's beeing created by FrameworkBundle and you should only inject event_dispatcher
service into whatever you need.
Otherwise, you can get lost very quickly with different scopes (each dispatcher has it's own subscribers and it's own events), and besides, it' sa waste of resources.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.