3 namespace Drupal\Core\EventSubscriber;
5 use Symfony\Component\DependencyInjection\ContainerAwareInterface;
6 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
7 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8 use Symfony\Component\HttpKernel\Event\PostResponseEvent;
9 use Symfony\Component\HttpKernel\KernelEvents;
12 * Destructs services that are initiated and tagged with "needs_destruction".
14 * @see \Drupal\Core\DestructableInterface
16 class KernelDestructionSubscriber implements EventSubscriberInterface, ContainerAwareInterface {
18 use ContainerAwareTrait;
20 * Holds an array of service ID's that will require destruction.
24 protected $services = [];
27 * Registers a service for destruction.
29 * Calls to this method are set up in
30 * RegisterServicesForDestructionPass::process().
33 * Name of the service.
35 public function registerService($id) {
36 $this->services[] = $id;
40 * Invoked by the terminate kernel event.
42 * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
45 public function onKernelTerminate(PostResponseEvent $event) {
46 foreach ($this->services as $id) {
47 // Check if the service was initialized during this request, destruction
48 // is not necessary if the service was not used.
49 if ($this->container->initialized($id)) {
50 $service = $this->container->get($id);
57 * Registers the methods in this class that should be listeners.
60 * An array of event listener definitions.
62 public static function getSubscribedEvents() {
63 // Run this subscriber after others as those might use services that need
64 // to be terminated as well or run code that needs to run before
66 $events[KernelEvents::TERMINATE][] = ['onKernelTerminate', -100];