1

The EventSubscriberInterface can be used to listen for events, and getSubscribedEvents is used to announce which events an implementation would like to subscribe to.

The getSubscribedEvents must return an array which holds the type of events an implementation would like to subscribe to, as well as the function which is to be invoked when an event triggers.

  public static function getSubscribedEvents() {
    return [
      KernelEvents::REQUEST => [
        ['redirectToLoginPage'],
      ]
    ];
  }

The documentation is very sparse on the function :

The method name to call (priority defaults to 0)

By looking at other implementations, I see that the function may return TRUE, FALSE and even implementations of Response. An example implementation could thus look like this :

public function redirectToLoginPage(GetResponseEvent $event) {
  $random = rand(0,2);
  switch($random) {
    case 0:
      return TRUE;
    case 1:
      return FALSE;
    case 2:
     $response = new RedirectResponse('/user/login', 301);
     $event->setResponse($response);
     return TRUE;
  }
}

What is the "contract" for the function which subscribes to events? Specifically, what is the impact of returning TRUE and/or FALSE from this function?

2

The contract is the event class itself. In case of GetResponseEvent (deprecated by the way and will be replaced by RequestEvent in future Drupal releases) you can set a response, this will stop the propagation of this event and the kernel will return the response as an answer to the request.

From where do you have the example code, I'm not sure what case 0/1 is trying to do? In the Symfony default dispatcher the return value is ignored.

2
  • the example code is something I made up, based on a project I work on. The randomness is just something i added here in an attempt to explain the three types of return values I've seen returned from the callback function. That project returns TRUE and FALSE from the callback function. However, I could not figure out what TRUE and FALSE in this context signalled. Should the function either set a response on the passed event, or just return (with no return value)? – sbrattla Sep 2 '20 at 7:45
  • 1
    Yes, just return. The event dispatcher polls all event listeners until one stops propagation, which for this specific event is possible by setting a response. – 4k4 Sep 2 '20 at 8:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.