Custom router with a front controller in Magento 2:

Front controller architecture in Magento 2 and its flow:

overview of the front controller architecture in Magento 2 and its flow:

  1. Request Routing: When a user sends a request to a Magento 2 website, the request is first passed through the web server and reaches the Magento 2 application. The request is then routed to the appropriate controller based on the requested URL and the Magento 2 routing configuration.
  2. Front Controller: The front controller is a single point of entry for all requests in Magento 2. It handles the incoming requests and dispatches them to the appropriate controllers. The front controller is located at Magento\Framework\App\FrontControllerInterface.
  3. Routing: The front controller checks the request URL against the routing configuration defined in the routes.xml file of the module. If there is a match, the front controller passes the request to the corresponding controller.
  4. Controllers: Magento 2 controllers are responsible for handling specific requests from users. They contain methods that process and output the data for a specific request. Magento 2 controllers are located in the Controller directory of each module.
  5. Dependency Injection: Controllers and other classes in Magento 2 use dependency injection to access the objects they need to function. Dependency injection allows Magento 2 to be flexible and modular, and helps with testing and maintaining code.
  6. Models: Models in Magento 2 are responsible for managing data and business logic. They interact with the database, process data, and perform calculations. Magento 2 models are located in the Model directory of each module.
  7. Views: Views in Magento 2 are responsible for rendering HTML output. They take data from the controllers and models, and generate HTML markup that is sent back to the user’s browser. Magento 2 views are located in the view directory of each module.
  8. Layout: The layout file is responsible for defining the structure of the HTML output. It contains instructions on how to render the various components of a page, including the header, footer, and main content area. Layout files in Magento 2 are located in the view/frontend or view/adminhtml directory of each module.
  9. Blocks: Blocks in Magento 2 are PHP classes that contain business logic and are responsible for generating HTML output. They can be used to define reusable components that can be used across multiple pages. Magento 2 blocks are located in the Block directory of each module.
  10. Templates: Templates in Magento 2 are responsible for defining the HTML markup that will be used to generate the final output. They are typically used in combination with blocks, and are located in the view/frontend/templates or view/adminhtml/templates directory of each module.
  11. Response: The final HTML output generated by the views is sent back to the user’s browser as a response. The response may also contain cookies, headers, and other metadata.

In summary, the front controller architecture in Magento 2 is designed to provide a flexible and modular system for handling requests and generating HTML output. It uses routing, controllers, models, views, blocks, and templates to process and render data, and relies on dependency injection and the layout file to manage the flow of information.

Step-by-step guide on how to create a custom router with a front controller in Magento 2:

  1. Create a new module or navigate to an existing module you want to add the custom router to. In this example, let’s say the module is called Vendor_Module.
  2. In the module’s etc directory, create a new file called di.xml. The file path will be something like app/code/Vendor/Module/etc/di.xml.
  3. In di.xml, define a new preference for the Magento\Framework\App\RouterInterface interface. For example:
<preference for="Magento\Framework\App\RouterInterface" type="Vendor\Module\Controller\Router" />
XML

In this example, we’re defining a new preference for the RouterInterface that points to a custom router class called Vendor\Module\Controller\Router.

  1. Create a new file called Router.php in the module’s Controller directory. The file path will be something like app/code/Vendor/Module/Controller/Router.php.
  2. In Router.php, define the custom router class and extend the Magento\Framework\App\Router\Base class:
<?php
namespace Vendor\Module\Controller;

use Magento\Framework\App\ActionFactory;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\App\Router\Base;

class Router extends Base
{
    protected $actionFactory;

    public function __construct(ActionFactory $actionFactory)
    {
        $this->actionFactory = $actionFactory;
    }

    public function match(RequestInterface $request)
    {
        // Implement custom routing logic here
        // Return false if the router doesn't match the request
        // Otherwise, return an array with the following keys:
        // - module
        // - controller
        // - action
        // - parameters
    }
}
PHP

In this example, we’re defining a new router class that extends the Base router. We’re also injecting an ActionFactory object, which we’ll use to create a new controller instance.

  1. In the match() method of Router.php, implement the custom routing logic. The method should return an array with the following keys:
  • module: The name of the module that will handle the request.
  • controller: The name of the controller class that will handle the request.
  • action: The name of the action method that will handle the request.
  • parameters: An array of additional parameters to pass to the action method.

For example:

public function match(RequestInterface $request)
{
    $identifier = trim($request->getPathInfo(), '/');
    if (strpos($identifier, 'customroute') === 0) {
        $request->setModuleName('vendor_module');
        $request->setControllerName('index');
        $request->setActionName('custom');
        $request->setParams(['identifier' => $identifier]);
        return $this->actionFactory->create('Magento\Framework\App\Action\Forward', ['request' => $request]);
    }
    return false;
}
PHP

In this example, we’re checking if the request URL starts with the string “customroute”. If it does, we’re setting the module, controller, and action values and passing an additional parameter called identifier. We’re also returning an instance of the Forward action, which will forward the request to the appropriate controller.

  1. Create a new file called Index.php in the module’s Controller directory. The file path will be something like app/code/Vendor/Module/Controller/Index.php.
  2. In Index.php, define the controller class and implement the custom action method:
<?php
namespace Vendor\Module\Controller;

use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class Index extends \Magento\Framework\App\Action\Action
{
    protected $resultPageFactory;

    public function __construct(Context $context, PageFactory $resultPageFactory)
    {
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
    }

    public function execute()
    {
        // Get the identifier parameter from the request
        $identifier = $this->getRequest()->getParam('identifier');

        // Implement custom action logic here
        // Create a new result page and return it
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('Custom Page'));
        return $resultPage;
    }
}
PHP

In this example, we’re defining a new controller class that extends the Action class. We’re also injecting a PageFactory object, which we’ll use to create a new result page.

  1. In the execute() method of Index.php, implement the custom action logic. For example, you could use the identifier parameter to load data from a custom table and display it on the page.
  2. That’s it! Now you should be able to access your custom route at the URL http://example.com/customroute/identifier.
Scroll to Top