Reputation: 2368
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:
What is the best way of doing the EventSubscribers the best way?
Upvotes: 0
Views: 612
Reputation: 224
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.
Upvotes: 1