d8 dispatcher / subscriber
TRANSCRIPT
Drupal 8 Hooks or Events
Drupal is in its 8th version and we are seeing a shift away from many Drupalisms towards more modern PHP architectural decisions.
1. Using PSR-4 for autoloading.2. Plugins and annotations are taking away much of the need for info hooks.3. Dependency injection.4. Event Dispatcher and Subscriber.5. PHPUnit.6 Guzzle etc….
Example
Event Dispatcher and Event Subscriber
Why Event Dispatcher / Subscriber ?1. Developer (not drupal background) can easily
understand.2. More industry standard approach.3. Used by Laravel, Zend, Symphony etc. frameworks.4. In Drupal 9, we may not see hook system.5. If you are thinking to create your own framework/cms.6. Inbox performance.
Benefits of Event driven approach1.Lazy Loading2.Stopping Propagation3.Priority
Prerequisite1.OOPS Concept2.Service Container
Event Dispatcher
The EventDispatcher component provides tools that allow your application components to communicate with each other by dispatching events and listening to them.
1. It uses symphony’s EventDispatcherInterface to implement this.
2. Tag service with ‘event_dispatcher’.3. Uses dispatch() method to trigger events.
Dispatch an Event1. Get the instance of Event dispatcher :- $dispatcher = \Drupal::service('event_dispatcher');
2. Dispatch the event. $dispatcher->dispatch(‘my_event’, $e);
Dispatch Method
Dispatch method take two arguments - a. Event Nameb. Event Object
Event Naming Convention1. Must be unique.2. use only lowercase letters, numbers, dots (.), and
underscores (_);3. prefix names with a namespace followed by a dot (e.g.
kernel.);4. end names with a verb that indicates what action is
being taken (e.g. request).
Few Symphony Events Example - 1.KernelEvents::Request2.KernelEvents::Response3.KernelEvents::Controller4.KernelEvents::View5.KernelEvents::Terminate
Event ObjectIt contains the detail that dispatcher passes to the subscriber.
It should be an instance of a class extending symphony’s Event base class.
Event SubscriberAn event subscriber is a PHP class that's able to tell the dispatcher exactly which events it should subscribe to.
Define Event Subscriber1. Implements EventSubscriberInterface2. Tag service as ‘event_subscibe’.
Register Subsciber1.$dispatcher->addListener('my.event',
array($listener, 'onMyAction'));2.Static getSubscribedEvents() method.
public static function getSubscribedEvents() {$events[DummyEvents::DUMMY_CONFIG_SAVED]
[] = array('onConfigSave', 0);return $events;
}
1.Dummy sample code -https://github.com/joshirohit100/event_example
2. Documentation - https://api.drupal.org/api/drupal/core!modules!system!core.api.php/group/events/8
Thankyou