Answer the question
In order to leave comments, you need to log in
Using exception to redirect/return result in Symfony 2
Good day to all!
As far as I understand, in Symfony 2 there is no native way to return a Response from a service, or from a nested function. There should always be a check in the Action's main method and return the result from it.
This is very inconvenient, for example, when there is a service that performs some initial initialization and, as a result of input data validation, may require a redirect to another page. It is necessary to insert a check on the return value of the service method into all controller methods where initialization is performed.
There is a solution, but it seems very "crooked" to me (I like that not only the design of the code is beautiful, but the code itself is not "Hindu"). So, this solution is its own EventListener, its own Exception, during the processing of which a redirect to the desired page will be called.
I really don’t like the attempt to “ride the river on a bicycle”, but I don’t see any other solution.
Perhaps it is, since my study of symfony is still ongoing.
PS Carrying out the initial initialization in the controller is not an option for the same reason, since if it (initialization) is in a function, then it will be necessary to check the result of this function every time, in each Action method and act according to the result.
Answer the question
In order to leave comments, you need to log in
Returning a method, either Response or something else, is also a crooked approach. Why not subscribe to the kernel.request event, which occurs before the action in the controller is executed. And check the input data, in case they are not satisfied with returning a Response and then the controller will not be called.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question