This commit is contained in:
Oliver Davies 2018-08-21 13:32:58 +01:00
parent ba77b765e6
commit a8ae47e330
3 changed files with 68 additions and 0 deletions

View file

@ -0,0 +1,68 @@
---
title: Experimenting with events in Drupal 8
tags:
- drupal
- drupal-8
- symfony
- php
---
{% block excerpt %}
Ive been experiementing with moving some of the code to Drupal 8, and Im quite intrigued by a different way that Ive tried to structure it - building on some of the takeaways from Drupal Dev Days.
{% endblock %}
{% block content %}
Here is how this module is currently structured:
![](/assets/images/blog/events-drupal-8/1.png){.border .p-1}
Note that there is no `opdavies_blog.module` file, and rather than calling actions from within a hook like `opdavies_blog_entity_update()`, each action becomes its own event subscriber class.
This means that there are no long `hook_entity_update` functions, and instead there are descriptive, readable event subscriber class names, simpler action code that is responsibile only for performing one task, and youre able to inject and autowire dependencies into the event subscriber classes as services - making it easier and cleaner to use dependency injection, and simpler write tests to mock dependencies when needed.
The additional events are provided by the [Hook Event Dispatcher module][0].
## Code
`opdavies_blog.services.yml`:
```yaml
services:
Drupal\opdavies_blog\EventSubscriber\PostTomedium:
autowire: true
tags:
- { name: event_subscriber }
Drupal\opdavies_blog\EventSubscriber\SendTweet:
autowire: true
tags:
- { name: event_subscriber }
```
`src/EventSubscriber/SendTweet.php`:
```php
namespace Drupal\opdavies_blog\EventSubscriber;
use Drupal\hook_event_dispatcher\Event\Entity\EntityUpdateEvent;
use Drupal\hook_event_dispatcher\HookEventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class SendTweet implements EventSubscriberInterface {
...
public static function getSubscribedEvents() {
return [
HookEventDispatcherInterface::ENTITY_UPDATE => 'sendTweet',
];
}
public function sendTweet(EntityUpdateEvent $event) {
// Perform checks and send the tweet.
}
}
```
{% endblock %}
[0]: https://www.drupal.org/project/hook_event_dispatcher

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB