Le code suivantabonné Symfony EventDispatcher ne fonctionnent pas
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');
}
}
il suppose d'envoyer un événement TransactionCreated
et se faire prendre par la classe elle-même et la fonction onCreatedNewTransaction
s'appeler afin de définir les propriétés de la classe.
La classe Transaction
instancié comme
$Transaction = Transaction::CreateNewTransaction('6/6/2016', 'John'....);
mais quand je déboguer le projet l'objet $Transaction
ont null
valeurs. J'ai placé une méthode breakpoint
à onCreateNewTransaction
et j'ai trouvé que ainsi la fonction n'est pas invoquée.
MISE À JOUR
Problème résolu
`onCreateNewTransaction » devraient être rendus publics au lieu de privé
Il se peut que je manque quelque chose, mais pourquoi avez-vous besoin d'un événement dans ce scénario? Cela n'aurait-il pas plus de sens d'assigner ces propriétés au constructeur? En dehors de cela, vous devez injecter EventDispatcher au lieu de l'instancier dans le constructeur, de cette façon vous créez une dépendance fixe. –