1

I am trying to create a basic event subscriber, but when I add the services.yml file and attempt to rebuild the cache with drush cr, I get this error.

In Drupal.php line 130:

\Drupal::$container is not initialized yet. \Drupal::setContainer() must be called with a real container.

If I clear the cache from Drupal, it works fine, but Drush always errors out. If I remove the services file, Drush works fine again.

Has anyone seen this before? I don't want to move forward without resolving this. I have added services and event subscribers in this project before without an issue. I double checked spacing structure, etc.

module/gary_custom.services.yml

services:
  gary_custom.custom_event_subscriber:
    class: Drupal\gary_custom\EventSubscriber\CustomEventSubscriber
    tags:
      - { name: event_subscriber }

module/src/EventSubscriber/CustomEventSubscriber.php

namespace Drupal\gary_custom\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;

class CustomEventSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    \Drupal::logger('debug')->debug('get sub events');

    $events[KernelEvents::REQUEST][] = array('checkForRedirection');
    return $events;
  }

  /**
   * This method is called whenever the KernelEvents::REQUEST event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function checkForRedirection(GetResponseEvent $event) {
    \Drupal::logger('debug')->debug('hitting');
  }
}

I am using Drush 9.4.0.

2
  • 4
    Have you tried without the logging lines? In the getSubscribedEvents method in particular?
    – Clive
    Mar 5, 2019 at 20:03
  • Wow weird that was totally it thank you. Post your answer when you get a sec @Clive Mar 6, 2019 at 15:59

1 Answer 1

1

The problem is the logging line in getSubscribedEvents:

\Drupal::logger('debug')->debug('get sub events');

Drupal::logger queries the container for a service, but the container hasn't been set at the point the event subscriber discovery happens.

By the time the event handler is invoked, the container has been initialised, so the logging in checkForRedirection should work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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