https://m.academy/articles/magento-2-request-response-lifecycle/
https://tiagosampaio.com/2023/06/19/front-controller-the-guy-who-handles-the-request-in-magento-2/
Types of Controller Response in Magento 2
There are five Controller Response Types in Magento
- Page
- JSON
- ROW
- Redirect
- Forward
(01) Page: This returns HTML loaded from a layout handle.
(02) JSON: this returns a response in JSON format. It can be used in API or AJAX requests.
Magento\Framework\Controller\Result\JsonFactory;
$result = $this->jsonFactory->create();
$data = ['success' => true, 'message' => 'Data fetched successfully']; return $result->setData($data);
(03) Raw: this returns whatever you want to be returned.
Magento\Framework\Controller\Result\RawFactory;
$result = $this->rawFactory->create();
$result->setHeader('Content-Type', 'text/plain');
$result->setContents('This is a plain text output'); return $result;
(04) Forward: this internally forwards to another controller without changing the URL.
Magento\Framework\Controller\Result\ForwardFactory;
$result = $this->forwardFactory->create();
return $result->forward('newAction');
Magento\Framework\Controller\Result\RedirectFactory;
$result = $this->redirectFactory->create();
return $result->setUrl('/some-other-url');
Front Controller
In apps, routing is usually handled by what’s known as a “front controller”, which is the first place of entry for a request. Magento is no different. The front controller is responsible for taking the incoming request and figuring out how to handle it.
In Magento, the front controller class is located at Magento\Framework\App\FrontController
. This file is the brains behind the routing process. When the front controller receives a request, it works with some other components to determine the route that is responsible for handling it.
The dispatch
method of the FrontController
class is the part of code which executes an action to generate a response:
Routing in Magento 2 is based on Front Controller Pattern.
The front controller design pattern means that all requests that come for a resource in an application will be handled by a single handler and then dispatched to the appropriate handler for that type of request.
FrontController iterates via the available routers and, if the action responsible for the current URL is successfully found, calls the \Magento\Framework\App\Action\AbstractAction::dispatch
method.
You need to handle URLs that don’t follow the typical module/controller/action
format (e.g., /some-review/123
).