Forked from DianaSchef/symfony_event_dispatcher_lazy_listener.php
Created
November 22, 2025 19:22
-
-
Save graste/fe0acc35bfdbf105535ccd62d7f3d4ed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| // This code is what the Symfony Dependency Injection container performs | |
| // under the hood when registering a listener. | |
| $eventDispatcher->addListener( | |
| KernelEvents::REQUEST, | |
| function ($event) { | |
| // only when here, MyListener and ExpensiveDependency trigger autoloading | |
| // and the time of calling their constructor is spent. | |
| (new MyListener(new ExpensiveDependency))->onKernelRequest($event); | |
| }, | |
| ); | |
| // dispatch "unwraps" the listener by calling the closure, only then MyListener | |
| // and the ExpensiveDependency are created. | |
| $eventDispatcher->dispatch( | |
| new RequestEvent(/** ... */), KernelEvents::REQUEST) | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment