How to create Controllers in Magento 2

Controller specially is one of the important thing in Magento 2 module development, and PHP MVC Framework in general. It functionarity is that received request, process and render page.

In Magento 2 Controller has one or more files in Controller folder of module, it includes actions of class which contain execute() method. There are 2 different controllers, they are frontend controller and backend controller. They are generally similar of workflow, but admin controller is a little different. There is a checking permission method in admin controller. Let’s take an example:

protected function _isAllowed()
    return $this->_authorization->isAllowed('Magento_AdminNotification::show_list');

It will check the current user has right to access this action or not.

How controller work?

It receive an request from end-user (browser or comamnd line), for example:
  • route_name is a unique name which is set in routes.xml.
  • controller is the folder inside Controller folder.
  • action is a class with execute method to process request.

One of the important in Magento system is frontController (Magento\Framework\App\FrontController), it alway receive request then route controller, action by route_name Let take an example of routing an request:

foreach ($this->_routerList as $router) {
   try {
      $actionInstance = $router->match($request);

If there is an action of controller class found, execute() method will be run.

How to create a controller?

To create a controller, we need to create a folder inside Controller folder of module and declare an action class inside it. For example, we create a Test controller and a Hello action for module Mageplaza_HelloWorld:


And content of this file should be:

namespace Mageplaza\HelloWorld\Controller\Test;
class SayHello extends \Magento\Framework\App\Action\Action
	public function execute()
		echo 'Hello World! Welcome to';

As you see, all controller must extend from \Magento\Framework\App\Action\Action class which has dispatch method which will call execute method in action class. In this execute() method, we will write all of our controller logic and will return response for the request.

Forward and redirect in action.

\Magento\Framework\App\Action\Action class provide us 2 important methods: _forward and _redirect.

Forward method

_forward() protected function will edit the request to transfer it to another controller/action class. This will not change the request url. For example, we have 2 actions Forward and Hello World like this:

namespace Mageplaza\HelloWorld\Controller\Test;
class Forward extends \Magento\Framework\App\Action\Action
	public function execute()

If you make a request to , here are result will be displied on the screen.

Hello World! Welcome to

You can also change the controller, module and set param for the request when forward. Please check the _forward() function for more information:

protected function _forward($action, $controller = null, $module = null, array $params = null)
    $request = $this->getRequest();


    if (isset($params)) {

    if (isset($controller)) {

        // Module should only be reset if controller has been specified
        if (isset($module)) {


Redirect method

This method will transfer to another controller/action class and also change the response header and the request url. With above example, if we replace _forward() method by this _redirect() method:


Then after access from the url, the url will be change to and show the message Hello World! Welcome to on the screen.

How to rewrite controller in Magento 2

To rewrite controller, you can do it by using preference. It mean that you need to put a rule in your router config using before attribute.

Open Mageplaza/HelloWorld/etc/di.xml insert the following block of code inside <config> tag rewrite controller in Magento 2

<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">

<router id="standard">
    <route id="mageplaza" frontName="hello">
       <module name="Mageplaza_HelloWorld" before="Magento_Customer" />


This will completely change controller/action of module Magento_Customer with your controller code, so you should extend rewrite controller and make a change on the function which you want. Also, the controller and action in your module must have same name with rewrite controller/action. For example, if you want to rewrite controller: Magento\Customer\Controller\Account\Create.php

You have to register a router like above and create a controller:


Content of Create.php file:

namespace Mageplaza\HelloWorld\Controller\Account;

use Magento\Customer\Model\Registration;
use Magento\Customer\Model\Session;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;

class Create extends \Magento\Customer\Controller\AbstractAccount
    /** @var Registration */
    protected $registration;

     * @var Session
    protected $session;

     * @var PageFactory
    protected $resultPageFactory;

     * @param Context $context
     * @param Session $customerSession
     * @param PageFactory $resultPageFactory
     * @param Registration $registration
    public function __construct(
        Context $context,
        Session $customerSession,
        PageFactory $resultPageFactory,
        Registration $registration
    ) {
        $this->session = $customerSession;
        $this->resultPageFactory = $resultPageFactory;
        $this->registration = $registration;

     * Customer register form page
     * @return \Magento\Framework\Controller\Result\Redirect|\Magento\Framework\View\Result\Page
    public function execute()
        if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
            /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
            $resultRedirect = $this->resultRedirectFactory->create();
            return $resultRedirect;

        /** @var \Magento\Framework\View\Result\Page $resultPage */
        $resultPage = $this->resultPageFactory->create();
        return $resultPage;

Enjoyed the tutorial? Spread it to your friends!


Comments for How to create Controllers in Magento 2

Please leave comments if you have any questions, feedbacks.

You also may like these Magento 2 Extensions

One Step Checkout

10 reviews

Layered Navigation

12 reviews


6 reviews


3 reviews


10 reviews

Zoho CRM

3 reviews

Store Locator

1 review

Shop By Brand

no review