Skip to content

For most use cases, Notifier provides a method for mapping information from objects and producing recipients from them, as described in previous pages.

To have more control in complex use cases, an event subscriber can be implemented:

Event subscriber

yaml
services:
  _defaults:
    autoconfigure: true
    autowire: true
    
  Drupal\my_module\EventListener\MyRecipients: ~
php
namespace Drupal\my_module\EventListener;

use Drupal\notifier\Recipients\Event\Recipients;
use Drupal\notifier\Recipients\Recipient\EmailRecipient;
use Drupal\user\UserInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

final class MyRecipients implements EventSubscriberInterface {
  public function onRecipient(Recipients $event): void {
    // $event->for is the object we are producing recipients for.
    if ($event->for instanceof SomeCriteria) {
      $recipient = new MyRecipientObject();
      $event->addRecipient($recipient);
    }
  }

  public static function getSubscribedEvents(): array {
    // Listen for the Recipients event:
    return [Recipients::class => 'onRecipient'];
  }
}

Event

The event has the following public API surface. See source code for further documentation.

php
\Drupal\notifier\Recipients\Event\Recipients {
  public function addRecipient(RecipientInterface $recipient);
  public function removeRecipient(RecipientInterface $recipient);
  public function getRecipients(): iterable;
}

Adding recipients

Add a recipient by calling $event->addRecipient($recipient). The recipient object is an object implementing \Symfony\Component\Notifier\Recipient\RecipientInterface. See more information on recipient interfaces.

WARNING

Do not call $event->addRecipient() unless you have a fully valid recipient.

WARNING

Do not create recipients which produce empty values (empty-string, NULL, FALSE, etc).

Recipient objects implementing \Symfony\Component\Notifier\Recipient\RecipientInterface should be created and maintained in your own project.

DANGER

Do not create instances of recipient objects owned by Notifier or SMS Framework. They are marked as @internal and are subject to change or removal at any time. Instead, create your own. Internal recipients include at time of writing:

  • \Drupal\notifier\Recipients\Recipient\EmailRecipient
  • \Drupal\notifier\Recipients\Recipient\SmsRecipient
  • \Drupal\sms\PhoneNumber\RecipientProxy