On Github lunika / thelia-slides-apihour9
E-Commerce solution based on Symfony 2 components
By Manuel Raynaud / @manuraynaud
Clemont'ech APIHour #9 28/05/2014
MyModule MyModule.php Config config.xml module.xml routing.xml schema.xml Controller MyModuleAdminController.php I18n fr_FR.php en_US.php Model Base Map MyModule.php MyModuleQuery.php Listeners CartListener.php OrderListener.php Loop MyModuleLoop.php templates ...
//depuis le container $eventDispatcher = $container->get('event_dispatcher'); //depuis un event $eventDispatcher = $event->getDispatcher();
1 event = 1 classe de données
<?php namespace Thelia\Core\Event; use Symfony\Component\EventDispatcher\Event; class Cart extends Event { protected $productId; protected $quantity; public function __construct($productId, $quantity) { $this->productId = $productId; $this->quantity = $quantity; } public function getProductId() { return $this->productId; } public function getQuantity() { return $this->quantity; } }
use Thelia\Core\Event\Cart; use Thelia\Core\Event\TheliaEvents; // $eventDispatcher = $container->get('event_dispatcher'); $cartEvent = new Cart(1, 3); $eventDispatcher->dispatch(TheliaEvent::CART_ADD, $cartEvent);
<?php namespace MyModule\Listener; use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\CartEvent; Class CartListener implements EventSubscriberInterface { public static function getSubscribedEvents() { return [ TheliaEvents::CART_ADD => ['addItem', 100] ]; } public function addItem(CartEvent $event) { $item = $event->getCart()->getLast(); $item->addQuantity(rand(1,5)); $item->save(); } }
<service id="MyModule.cart.listener" class="MyModule\Listener\Cart"> <tag name="kernel.event_subscriber"/> </service>
Rien ne vous assure que votre listener sera exécuté
Il suffit de créer un fichier routing.xml dans le répertoire Config
<!--?xml version="1.0" encoding="UTF-8" ?--> <routes xmlns="http://symfony.com/schema/routing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd"> <route id="mumodule.id" path="/foo"> <default key="_controller"> MyModule\Controller\MyModuleAdminController::fooAction </default> </route> </routes>
Config personnalisée
<service id="router.front" class="%router.class%"> <argument type="service" id="router.module.xmlLoader"> <argument>MyModule/Config/custom_routing.xml</argument> <argument type="collection"> <argument key="cache_dir">%kernel.cache_dir%</argument> <argument key="debug">%kernel.debug%</argument> </argument> <argument type="service" id="request.context"> <tag name="router.register" priority="256"> </tag></argument></argument></service>