
Lee RowlandsSenior Developer
Drupal 8 comes with two extension points for module developers to allow other modules to interact with their code.
The trusty alter hook, the linchpin of Drupal versions past is still there - allowing other modules to interact and intervene in the behaviour of your module.
But there is a new kid on the block, the event system.
So as a module developer how do you decide whether to use the alter system or the event system.
This was the premise of a recent IRC conversation between myself, dawehner and bojanz, so for posterity I present to you the pros and cons we came up with.
<?php
function mymodule_dosomething() {
$data = mymodule_get_some_data();
return \Drupal::moduleHandler()->alter('my_module_hook', $data);
}
?>
<?php
namespace Drupal\mymodule;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Drupal\mymodule\Events\SomethingEvent;
/**
* Defines a class for doing stuff.
*/
class MyModuleSomething {
protected $eventDispatcher;
/**
* Constructs a MyModuleSomething.
*/
public function __construct(EventDispatcherInterface $event_dispatcher) {
$this->eventDispatcher = $event_dispatcher;
}
/**
* Does something.
*/
public function doSomething($with_this) {
$event = new SomethingEvent($with_this);
$this->eventDispatcher->dispatch(SomethingEvent::JUST_DO_IT, $event);
return $event->showMeTheDoneStuff();
}
}
?>
Are you building a module for Drupal 8 and have already decided to use events instead of alter hooks? Let us know what influenced your decision in the comments - let's keep the conversation going and build out a resource to help others make their decision.