Magento 2 Request Flow

URLs in Magento have the format of <AreaName>/<ModuleFrontName>/<ControllerName>/<ActionName>

Magento process a URL request by first stripping of the base URL. The first path segment of the remaining URL identifies request area. For example, admin for adminhtml area, and none for frontend area.

After the area name, the URI segment specifies the frontname which defined in related module. For example, in catalog/product/view, catalog is the module frontname, product is the controller folder, and view is the controller class (replacing action in Magento 1).

We use the router class to assign a URL to a corresponding controller and its action. The router’s match method finds a matching controller, which is determined by an incoming request.

Creating Controller

Conceptually, creating a new controller is as simple as doing the following:

  • Register a route via router.xml
  • Create an abstract controllers file (as an abstract class, which extends \Magento\Framework\App\Action\Action). This file will act as the main controller.
  • Create separate action controller files (which extends the main controller file with execute method, and implements \Magento\Framework\App\ActionInterface).

Any Magento controller returns an instance of \Magento\Framework\Controller\ResultInterface:

  • json: \Magento\Framework\Controller\Result\Json
  • raw: \Magento\Framework\Controller\Result\Raw
  • redirect: \Magento\Framework\Controller\Result\Redirect
  • forward: \Magento\Framework\Controller\Result\Forward
  • layout: \Magento\Framework\View\Result\Layout
  • page: \Magento\Framework\View\Result\Page

Comparison with Magento 1 Actions

In Magento 1, we would create a single controller (e.g. CustomerController), containing functions of actions (e.g. saveAction, editAction, deleteAction, viewAction, etc).

But in Magento 2, we separate all of the actions into their own classes (Index, New, Edit,Delete,etc). This is where the main controller usage comes into play. We can put any function that shared among the actions in the main controller, and extends it in our actions.

 

Note: The separation of the controller into the main and action controller files is not a technical requirement, but rather a recommended organizational one. Magento does this accross the majority of its modules.

 

 

Series Navigation<< Magento 2 AreasMagento 2 Coding Standard >>

Leave a Reply