Last active
September 19, 2017 05:59
-
-
Save MaximStrutinskiy/571d1c3edba56911fc52d53665285f3b to your computer and use it in GitHub Desktop.
Event Dispatcher.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function indexAction(Request $request) | |
{ | |
$em = $this->getDoctrine()->getManager(); | |
$shipment = new Shipment(); | |
$form = $this->createFormBuilder($shipment) | |
->add('name', TextType::class) | |
->getForm(); | |
$form->handleRequest($request); | |
if ($form->isSubmitted() && $form->isValid()) { | |
$data = $form->getData(); | |
$shipment->setName($data->getName()); | |
$dispatcher = $this->get('event_dispatcher'); | |
$dispatcher->dispatch('generate.shipment', new GeneratePriceEvent()); | |
$em->persist($shipment); | |
$em->flush(); | |
} | |
return $this->render( | |
'MainBundle:Customer/page:test.html.twig', | |
[ | |
'form' => $form->createView(), | |
] | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MainBundle\Event; | |
use MainBundle\Entity\Price; | |
use Symfony\Component\EventDispatcher\Event; | |
class GeneratePriceEvent extends Event | |
{ | |
public function generate($value, $discount = null, $em) | |
{ | |
$price = new Price(); | |
$price->setValue($value); | |
$price->setDiscount($discount); | |
$em->persist($price); | |
$em->flush(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace MainBundle\Event; | |
use Doctrine\ORM\EntityManager; | |
class Generate | |
{ | |
protected $em; | |
public function __construct(EntityManager $em) | |
{ | |
$this->em = $em; | |
} | |
public function onCreateShipmentEvent(GeneratePriceEvent $event) | |
{ | |
$event->generate(10, 20, $this->em); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.test_listener: | |
class: MainBundle\Event\Generate | |
arguments: ["@doctrine.orm.entity_manager"] | |
tags: | |
- { name: kernel.event_listener, event: generate.shipment, method: onCreateShipmentEvent } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment