3 namespace Drupal\Core\EventSubscriber;
4 use Symfony\Component\DependencyInjection\ContainerAwareInterface;
5 use Symfony\Component\DependencyInjection\ContainerAwareTrait;
6 use Symfony\Component\EventDispatcher\EventSubscriberInterface;
7 use Symfony\Component\HttpKernel\Event\PostResponseEvent;
8 use Symfony\Component\HttpKernel\KernelEvents;
11 * Destructs services that are initiated and tagged with "needs_destruction".
13 * @see \Drupal\Core\DestructableInterface
15 class KernelDestructionSubscriber implements EventSubscriberInterface, ContainerAwareInterface {
17 use ContainerAwareTrait;
19 * Holds an array of service ID's that will require destruction.
23 protected $services = [];
26 * Registers a service for destruction.
28 * Calls to this method are set up in
29 * RegisterServicesForDestructionPass::process().
32 * Name of the service.
34 public function registerService($id) {
35 $this->services[] = $id;
39 * Invoked by the terminate kernel event.
41 * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
44 public function onKernelTerminate(PostResponseEvent $event) {
45 foreach ($this->services as $id) {
46 // Check if the service was initialized during this request, destruction
47 // is not necessary if the service was not used.
48 if ($this->container->initialized($id)) {
49 $service = $this->container->get($id);
56 * Registers the methods in this class that should be listeners.
59 * An array of event listener definitions.
61 public static function getSubscribedEvents() {
62 // Run this subscriber after others as those might use services that need
63 // to be terminated as well or run code that needs to run before
65 $events[KernelEvents::TERMINATE][] = ['onKernelTerminate', -100];