URLs in Magento have the format of
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
After the area name, the URI segment specifies the frontname which defined in related module. For example, in
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.
Conceptually, creating a new controller is as simple as doing the following:
- Register a route via
- 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
Any Magento controller returns an instance of
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.