07/12/2016

Magento 2 Controller Architecture

Controller architecture
Controller is a class specific to a URL or group of URLs. 
In Magento 2, a controller can only process a single action. Each Controller, or Action class includes:
  • a normal __construct() constructor used for injecting all necessary dependencies (as controller class is injectable)
  • a public execute() method that represents the action and contains necessary logic
  • extra private or protected methods and properties that help implementing controller logic.

Frontend Controller

Usually, frontend-related controllers extend \Magento\Framework\App\Action\Action, which, in its turn, is extended from two other abstract classes that implement \Magento\Framework\App\ActionInterface. It's very important to extend your frontend controllers from \Magento\Framework\App\Action\Action as it implements dispatch() method and extra important methods used by developers. The Router calls dispatch(), not execute() method when routing happens.
Sometimes, when it's impossible to extend \Magento\Framework\App\Action\Action, another class implementing \Magento\Framework\App\ActionInterface can be used. In that case the developer must implement the dispatch() method on his/her own.

Admin Controller

The difference of admin controller is that it requires to check a user permissions to decide whether the user is eligible to visit this controller. It also implements some admin panel-specific functionality. For that purpose, they are extended from \Magento\Backend\App\Action which has a modified dispatch() method which checks if the user logged in, and calls $this->_isAllowed() that checks if the ACL role of the current user is linked with the action to allow using it.
The admin action controller also has its own implementation for redirect() and forward() methods, as well as knows how to handle form keys.
There are also some auxiliary methods that can be used in the admin action controllers:
  • _getSession()
  • _addBreadcrumb()
  • _addJs()
  • _addContent()
  • _addLeft()
  • _getUrl()

Forwarding and Redirection

  • _forward() — is delegating execution to another action that correspond to the specified path. This happens inside of the FrontController and routing loop, it simply modifies the request object, tells the FrontController that the action was not dispatched, and route matching process starts anew.
  • _redirect() — is returning a Response object with redirect header set, after returning that object in the action, a real redirection is initiated instead of rendering a page.