To create a custom URL path (route) such as example.com/test/, use the following as a guide. This assumes you already have created a custom module with your three initial files (registration.php, composer.json and etc/module.xml) using a module called YourNamespace_TestRoute. This was written with Magento (Adobe Commerce) version 2.4.5.
1. Create Route Config etc/frontend/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="test" frontName="test">
<module name="YourNamespace_TestRoute"/>
</route>
</router>
</config>
id="test"
will give the route a unique identifier and determine the name of your layout XML file… In this case, the main index file will be test_index_index.xml because id
is set to test
.
2. Create Controller: Controller/Index/Index.php
<?php
declare(strict_types=1);
namespace YourNamespace\TestRoute\Controller\Index;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;
class Index implements HttpGetActionInterface
{
/**
* @var ResultFactory
*/
protected $resultFactory;
/**
* @param Context $context
*/
public function __construct(
Context $context
) {
$this->resultFactory = $context->getResultFactory();
}
/**
* Show page
*
* @return ResultInterface
*/
public function execute()
{
return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
}
}
3. Create Layout XML: view/frontend/layout/test_index_index.xml
<?xml version="1.0"?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<title>My Test Routing Page</title>
</head>
<body>
<referenceBlock name="page.main.title">
<action method="setPageTitle">
<argument translate="true" name="title" xsi:type="string">My Test Routing Page</argument>
</action>
</referenceBlock>
</body>
</page>
Remember the name of this file is determined by the route id defined in your routes.xml file followed by your controller names.
Optionally… instead of heading your page <title>
tag in the <head>
in XML here, you can also replace the return
of your execute()
method in your controller with…
$resultFactory = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
return $resultFactory->getConfig()->getTitle()->set(__('My Test Routing Page'));
4. Enable module and Setup
In your command line terminal, run the following…
$ bin/magento module:enable YourNamespace_TestRoute
$ bin/magento setup:upgrade