Maybe you can use the event dispacher component to create your own event, and dispatch it in the actions you want. Info here: The EventDispatcher Component
Response Event listener for a specific action
-
24-06-2023 - |
Question
I have an event listener, with a method looking like this
public function onKernelResponse(FilterResponseEvent $event,EntityManager $entityManager)
{
$controller = $event->getController();
if (!is_array($controller)) {
return;
}
if ($controller[0] instanceof UserController) {
//@TODO limit this for Controller action editUser() only
$response = $event->getResponse()->getContent();
$responseDecoded = json_decode($response);
if ($responseDecoded instanceof UserProperties) {
}
}
}
my services.yml looks like this
update_user_controller_listener_marking_tasks:
class: Company\UserResultBundle\EventListener\UserEditListener
arguments: [@doctrine.orm.entity_manager]
tags:
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
the problem is the listener runs for every action executed in that user controller, which i do not want.
My question is how I can limit to be running at the response of a specific action only. Let us say editUser()
?
I was not able to find this explicitly shown the documentation
Solution 3
OTHER TIPS
You can check $controller[1]
value - it contains controller's action method name:
if ($controller[0] instanceof UserController) {
// limit this for Controller action editUser() only
if ($controller[1] === 'editUserAction') {
...
How about throw a custom Exception and do this:
public function onKernelException(GetResponseForExceptionEvent $event)
{
// You get the exception object from the received event
$exception = $event->getException();
if('Some\Namespace\ApiException' == get_class($exception)){
$res = new JsonResponse([
'message'=>$exception->getMessage(),
], 500);
$event->setResponse($res);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow