Symfony2 eventdispatcher component

Source: Internet
Author: User

In a plug-in system, plug-in a adds a new method without affecting other plug-ins, or makes some preparations before running a method, it is not easy to implement extension through inheritance. Due to the association between plug-ins, changes to plug-ins A will also make passive modifications to the associated plug-ins. The eventdispatcher component of symfony2 implements the mediator mode and the decoupling and association between plug-ins. For example, in the httpkernel component, once the response is created, it is necessary and useful to allow other modules of the system to modify it when the response is sent to the client (for example: add cache fields in the header ). Symfony2 kernel scheduling kernel. RESPONSE event, then the listener that listens to this event can modify the response object: a) the listener (PHP Object) tells a specific dispatcher class that listens to the kernel. RESPONSE event; B) symfony will tell dispatcher to schedule the kernel at a certain time point. the response event is used to pass an event object containing the response object to the event scheduling method eventdispatcher: Dispatch () c) DISPATCHER to notify all listening kernel. the listener of the response event is running, allowing these listeners to modify the response object. Usage When an event is scheduled, the event has a unique name (for example, kernel. Response) and can be monitored by multiple listeners. Instantiate an event object and pass it into all listeners. The event object contains the data of the scheduled event. Naming rules The event name can be any string, but it can follow the naming rules below: * only lower-case characters, numbers, points, and underscores are used; * The prefix name must be a bit named; * The Name Of The end part uses a verb that can express the action of the current event; Event name and event object When the dispatcher schedules an Event Notification listener, an event object is passed into the listener as a parameter. The base class event is very simple. There is only one method to stop the event and pass it to the next Listener. Generally, the data of a specific event is stored in the event object, so that the data can be easily transmitted to the listener. In the kernel. RESPONSE event, the event object passed into the listener is the object of the subclass fliterresponseevent, and fliterresponseevent is the subclass of the event. Fliterresponseevent includes the getreponse and setresponse methods, allowing the listener to obtain or modify the response object. In general, when you create a listener to listen to a specific event, a subclass of the event will be passed into the listener, and the listener can obtain and modify information through this subclass. The dispatcher is the core of the event scheduling system. Generally, a dispatcher contains a list of listeners. When an event needs to be scheduled, the dispatcher notifies it of all the listeners that listen on the event.
1 use Symfony\Component\EventDispatcher\EventDispatcher;2 3 $dispatcher = new EventDispatcher();
The associated listener adds the listener to the dispatcher to listen for a specific event. When the event is scheduled, the dispatcher notifies the listener of its work. Dispatcher uses the addlistener method to add a listener (PhP callable) to an event.
1 $listener = new AcmeListener();2 $dispatcher->addListener(‘foo.action‘, array($listener, ‘onFooAction‘));
The addlistener method has three parameters: * The name of the event that the listener needs to listen to; * The Listener (a PHP callable); * an optional integer that indicates the priority (the higher the value, the higher the priority, the listener will be triggered earlier). The default value is 0. If the priority is the same, the listener will be triggered first when the listener is added first;
PHP callable is a PHP variable that can be passed into call_user_func () as a parameter or passed into the is_callable () function for execution and returns true. PHP callable can be an \ closure instance, an object that implements the _ invoke method, a string that represents a function, or an array that represents an object method or a class method. So far, we have seen a PHP Object as the listener, and we can also use the closure object as the listener.
1 use symfony \ component \ eventdispatcher \ event; 2 3 $ Dispatcher-> addlistener ('foo. action ', function (event $ event) {4 // will be executed when the foo. action event is dispatched5 });
In the preceding example, the foo. Action event is scheduled, and the dispatcher calls the acmelistener: onfooaction method, and passes the event object as a unique parameter to the method.
 1 use Symfony\Component\EventDispatcher\Event; 2  3 class AcmeListener 4 { 5     // ... 6  7     public function onFooAction(Event $event) 8     { 9         // ... do something10     }11 }

In actual use, all objects of a specific event subclass are passed to the listener, such as filterresponseevent:

1 use Symfony\Component\HttpKernel\Event\FilterResponseEvent;2 3 public function onKernelResponse(FilterResponseEvent $event)4 {5     $response = $event->getResponse();6     $request = $event->getRequest();7 8     // ...9 }
Apart from built-in system events, you can also create and schedule custom events. This is very beneficial. When we use third-party class libraries, we can also decouple different components to make the system more flexible and robust. For the static events class, if we want to create an event -- store. Order -- it will be triggered when the order is created.
namespace Acme\StoreBundle;final class StoreEvents{    /**     * The store.order event is thrown each time an order is created     * in the system.     *     * The event listener receives an     * Acme\StoreBundle\Event\FilterOrderEvent instance.     *     * @var string     */    const STORE_ORDER = ‘store.order‘;}
This class does not have any methods or operations, but defines the event name to facilitate event management and organization. All listeners that listen for this event will be passed in a filterorderevent object. Create an event object. When you schedule this new event, an event object will be created and passed to the dispatch () method of dispatcher, the dispatcher transmits the event object to all listeners listening to the event. If you do not need to input any information to the listener, you can use the system's default symfony \ component \ eventdispatcher \ event class. However, many times we need to input specific information to the listener, so we can create a class that inherits symfony \ component \ eventdispatcher \ event. For example, we need to input the order object in all listeners:
 1 namespace Acme\StoreBundle\Event; 2  3 use Symfony\Component\EventDispatcher\Event; 4 use Acme\StoreBundle\Order; 5  6 class FilterOrderEvent extends Event 7 { 8     protected $order; 9 10     public function __construct(Order $order)11     {12         $this->order = $order;13     }14 15     public function getOrder()16     {17         return $this->order;18     }19 }
All listeners can use the getorder method of filterorderevent to obtain the order object. The dispatch () method of the scheduling event dispatcher notifies the listener of all listeners of the given event. There are two parameters: one is the name of the event to be scheduled, and the other is the event object sent to all listeners.
 1 use Acme\StoreBundle\StoreEvents; 2 use Acme\StoreBundle\Order; 3 use Acme\StoreBundle\Event\FilterOrderEvent; 4  5 // the order is somehow created or retrieved 6 $order = new Order(); 7 // ... 8  9 // create the FilterOrderEvent and dispatch it10 $event = new FilterOrderEvent($order);11 $dispatcher->dispatch(StoreEvents::STORE_ORDER, $event);

The filterorderevent object is passed into the dispatch method as a parameter. Now, any listener listening to the store. Order event receives the filterorderevent object and calls the getorder method to obtain the order object.

1 // some listener class that‘s been registered for "store.order" event2 use Acme\StoreBundle\Event\FilterOrderEvent;3 4 public function onStoreOrder(FilterOrderEvent $event)5 {6     $order = $event->getOrder();7     // do something to or with the order8 }
The most common method for event subscribers to listen to events is to register a listener to dispatcher. A listener can listen to one or more events. Another way to listen to events is to use event subscriber. Event subscriber is a PHP class that can accurately tell dispatcher that it has subscribed to those events. Implement the eventsubscriberinterface interface, which has a static method getsubscriberdevents.
namespace Acme\StoreBundle\Event;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpKernel\Event\FilterResponseEvent;class StoreSubscriber implements EventSubscriberInterface{    public static function getSubscribedEvents()    {        return array(            ‘kernel.response‘ => array(                array(‘onKernelResponsePre‘, 10),                array(‘onKernelResponseMid‘, 5),                array(‘onKernelResponsePost‘, 0),            ),            ‘store.order‘     => array(‘onStoreOrder‘, 0),        );    }    public function onKernelResponsePre(FilterResponseEvent $event)    {        // ...    }    public function onKernelResponseMid(FilterResponseEvent $event)    {        // ...    }    public function onKernelResponsePost(FilterResponseEvent $event)    {        // ...    }    public function onStoreOrder(FilterOrderEvent $event)    {        // ...    }}

This listener class is very simple. It tells the dispatcher what events it listens for and how to trigger the listener events. The addsubscriber () method registers the subscriber to the dispatcher.

1 use Acme\StoreBundle\Event\StoreSubscriber;2 3 $subscriber = new StoreSubscriber();4 $dispatcher->addSubscriber($subscriber);
The dispatcher accurately registers the subscriber to the event returned by eventsubscriberinterface: getsubscriberdevents (). The eventsubscriberinterface: getsubscriberdevents () method returns an array. The array key corresponds to the event listened by the subscriber, value corresponds to a method or a group of methods that the subscriber processes the event call. In the above example, the method of a group of listeners corresponds to this event, and we can also set the priority to control the execution sequence of this group of methods. When the kernel. RESPONSE event is triggered , onKernelResponsePre , onKernelResponseMid , And onKernelResponsePost三个方法就会先后执行。In some cases, the listener can stop passing events to prevent future listeners from being called. In other words, the listener must notify the dispatcher to stop passing events to subsequent listeners. Implement the stoppropagation () method in the listener:
1 use Acme\StoreBundle\Event\FilterOrderEvent;2 3 public function onStoreOrder(FilterOrderEvent $event)4 {5     // ...6 7     $event->stopPropagation();8 }
Then, the listener listening for the store. Order event that has not been executed will not be executed. The ispropagationstopped () method can be used to determine whether an event is stopped.
1 $dispatcher->dispatch(‘foo.event‘, $event);2 if ($event->isPropagationStopped()) {3     // ...4 }

 

Symfony2 eventdispatcher component

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.