So in our Symfony application, we have several EventSubscribers. Some of them should only be triggered on our main website, some only on our admin section (all routes with /admin).
Now, most of the EventSubscribers are using KernelEvents::CONTROLLER, like this:
public static function getSubscribedEvents(): array {
return [
KernelEvents::REQUEST => 'onRequestEvent'
];
}
This however makes it so even on our non-/admin routes, this gets called. We do have a check in our onRequestEvent
function that returns if the requestUri doesn't contain /admin, but I find this a pretty bad way of doing it, since the services in the controller still gets injected.
public function onRequestEvent(RequestEvent $event) {
if (strpos($event->getRequest()->getRequestUri(), '/admin') === false) {
return;
}
// .. CODE HERE
}
My question is, is there a way to make EventSubscribers work on specific routes (or paths)? Or should I just keep it like this? Or is there a better way of doing it?
I was thinking these are my options:
- Keep it like this (and possibly make it so the services in the constructor gets injected a different way)
- Make a custom AbstractController which dispatches a custom Event to handle logic in that
- Dispatch a custom Event in every controller function (I would say this isn't the best but maybe it is)
What is the best way of doing the EventSubscribers the best way?
CodePudding user response:
You could create a custom event, let's say "FrontRequestEvent" and use a light subscriber to the Symfony RequestEvent to trigger it after you check the path.
public function onRequestEvent(RequestEvent $event) {
if (strpos($event->getRequest()->getRequestUri(), '/admin') === false) {
return;
}
// .. DISPATCH FrontRequestEvent EVENT HERE
}
Then, you can create a subscriber to your event, where you can inject all your dependencies. This way, you instantiate dependencies only when needed.