- Namespace and folder structure: Place your admin controllers within the
Controller/Adminhtml
folder of your module. The namespace should follow this pattern:Vendor\Module\Controller\Adminhtml
. - Inheritance: Inherit your custom admin controller class from the
\Magento\Backend\App\Action
class, which provides the required functionality for admin controllers. - Access control: To restrict access to your controller, define an
_isAllowed()
method in your admin controller class. This method should return a boolean value based on the ACL rules you set in your module’setc/acl.xml
file. For example:
protected function _isAllowed()
{
return $this->_authorization->isAllowed('Vendor_Module::custom_acl_rule');
}
- Proper routing: Define your custom admin routes in the
etc/adminhtml/routes.xml
file of your module. Make sure to use a unique frontName to avoid conflicts with other modules. - Use Action classes: Break down complex controller logic into smaller, more manageable Action classes. This will make your code more modular and easier to maintain.
- CSRF protection: Magento 2 admin controllers automatically include CSRF protection. However, if you need to disable CSRF validation for a specific action, you can override the
_createCsrfValidationException()
and_validateCsrfToken()
methods in your admin controller class. - Use ResultFactory for responses: Instead of directly manipulating the response object, use the ResultFactory class to create different types of responses, such as JSON, Raw, Redirect, and Forward.
- Dependency injection: Use constructor-based dependency injection to utilize Magento’s core and custom services. Avoid using the Object Manager directly in your controllers.
- Avoid direct use of $_POST and $_GET: Use
$this->getRequest()->getParam('paramName')
to get request parameters instead of directly accessing the superglobals. - Logging: Use Magento’s built-in logging system to log any errors or exceptions that occur in your controller actions. This will help in debugging and monitoring your module’s functionality.
And regarding actual implementation, controllers should extend the \Magento\Framework\App\Action\Action
class for frontend controllers or \Magento\Backend\App\Action
class for admin controllers, rather than directly implementing any specific interface like HttpGetActionInterface
.
However, starting from Magento 2.3, the use of HttpGetActionInterface
, HttpPostActionInterface
, HttpPutActionInterface
, and HttpDeleteActionInterface
is recommended to explicitly specify the HTTP request methods that your controller action should handle.
When you extend the \Magento\Framework\App\Action\Action
or \Magento\Backend\App\Action
class, you can additionally implement any of the above-mentioned interfaces to declare the allowed HTTP request method(s) for your controller action. This is particularly useful for security purposes and to prevent unintended access to your controller.