当前位置: 技术文章>> magento2中的设置自定义路由以及代码示例

文章标题:magento2中的设置自定义路由以及代码示例
  • 文章分类: Magento
  • 10806 阅读
系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》

本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。


在 Magento 2 中,您可以使用控制器和路由来创建自定义模块并实现自定义功能。以下是如何设置自定义路由的代码示例:


首先,您需要创建一个 routes.xml 文件来设置自定义路由。在您的模块的 etc/frontend 文件夹中创建此文件。

<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="custom" frontName="custom">
            <module name="Your_Module"/>
        </route>
    </router>
</config>

在 Controller 文件夹中创建您的控制器文件。例如,我们创建一个名为 Index 的控制器,并在其中添加一个名为 Index 的动作。

<?php
namespace Your\Module\Controller\Index;
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()
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('Custom Route Example'));
        return $resultPage;
    }
}

在上面的代码中,我们定义了 Index 控制器的 Index 动作。在这个动作中,我们将显示一个页面,并设置页面标题为“Custom Route Example”。


最后,我们需要在 di.xml 文件中注册控制器。

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Your\Module\Controller\Index\Index">
        <arguments>
            <argument name="context" xsi:type="object">Magento\Framework\App\Action\Context</argument>
            <argument name="resultPageFactory" xsi:type="object">Magento\Framework\View\Result\PageFactory</argument>
        </arguments>
    </type>
</config>

在上面的代码中,我们将 Index 控制器注册为一个对象,并指定它所需要的参数。


现在,您已经成功地创建了一个自定义路由,可以使用 http://yourstore.com/custom 访问它。


推荐文章