When I want to change to a page from another, I can find both $this->dispatcher->forward()
and $this->response->redirect()
. Both seem to work ok.
What's the difference between them, and when should I use one over the other?
Phalcon\Mvc\Dispatcher is the component responsible for instantiating controllers and executing the required actions on them in an MVC application. Understanding its operation and capabilities helps us get more out of the services provided by the framework.
So, after you do redirect or forward, you need to ensure that you code doesn't get executed only if that is part of the expected logic. In other words you don't have to return the result of return $this->response->redirect or return $this->dispatcher->forward .
Class Phalcon\Mvc\Dispatcher Dispatching is the process of taking the request object, extracting the module name, controller name, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller.
Broadly speaking, Redirect
will do an http redirection (with the header location). It means that the browser of the client will change the page. It processes to a new routing (it can also be used to go to another website) and the actual script will end.
Whereas Forward
is internal, the browser of the client wont see any difference, you just execute a different controller.The dispatch loop allows the user to forward the execution flow to another controller/action. This is very useful to check if the user can access to certain options, redirect users to other screens or simply reuse code. But, Keep in mind that making a “forward” is not the same as making an HTTP redirect. Although they apparently got the same result. The “forward” doesn’t reload the current page, all the redirection occurs in a single request, while the HTTP redirect needs two requests to complete the process.
Similar analogy can be shown in JSP as well,
The sendRedirect(String path)
method of HttpServletResponse
will tell the client that it should send a request to the specified path. So the client will build a new request and submit it to the server. The client's history will be updated so the forward and back buttons will work. This method is useful for redirecting to pages on other servers and domains.
The forward method of RequestDispatcher
will forward the ServletRequest
and ServletResponse
that it is passed to the path that was specified in getRequestDispatcher(String path).
The response will not be sent back to the client and so the client will not know about this change of resource on the server. This method is useful for communicating between server resources, (servlet to servlet). This method is faster than using sendRedirect
as no network round trip to the server and back is required.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With