Book Image

Drupal 10 Development Cookbook - Third Edition

By : Matt Glaman, Kevin Quillen
Book Image

Drupal 10 Development Cookbook - Third Edition

By: Matt Glaman, Kevin Quillen

Overview of this book

This new and improved third edition cookbook is packed with the latest Drupal 10 features such as a new, flexible default frontend theme - Olivero, and improved administrative experience with a new theme - Claro. This comprehensive recipe book provides updated content on the WYSIWYG (What You See Is What You Get) editing experience, improved core code performance, and code cleanup. Drupal 10 Development Cookbook begins by helping you create and manage a Drupal site. Next, you’ll get acquainted with configuring the content structure and editing content. You’ll also get to grips with all new updates of this edition, such as creating custom pages, accessing and working with entities, running and writing tests with Drupal, migrating external data into Drupal, and turning Drupal into an API platform. As you advance, you’ll learn how to customize Drupal’s features with out-of-the-box modules, contribute extensions, and write custom code to extend Drupal. By the end of this book, you’ll be able to create and manage Drupal sites, customize them to your requirements, and build custom code to deliver your projects.
Table of Contents (17 chapters)

Creating an event subscriber to react to events

Drupal has two ways of integrating various parts of the system: using hooks or events. Hooks have been a part of Drupal for its entire lifespan and events were introduced in Drupal 8. Unlike the hook system, which has implicit registration, the event dispatch system uses explicit registration for an event.

The events dispatcher system comes from the Symfony framework and allows components to easily interact with one another. Within Drupal, and integrated Symfony components, events are dispatched, and event subscribers can listen to the events and react to changes or other processes.

In this recipe, we will subscribe to the RequestEvent event, which fires when a request is first handled. If the user is not logged in, we will navigate them to the login page.

How to do it…

  1. Create src/EventSubscriber/RequestSubscriber.php in your module.
  2. Define the RequestSubscriber class, which implements the EventSubscriberInterface...