magento与别的框架的不同之处之一:路由规则通过xml文件进行配置 参考:《深入理解magento 第二章》
简单介绍magento的控制器。
controller文件
之前我们新成立的Nano公司建了如下的模块,

完善一下HelloWorldController
<?php
//自己定义的前台的控制器都应继承Mage_Core_Controller_Front_Action
//类名称的格式为:模块名字空间_模块名称_controller名称
class Nano_App_HelloWorldController extends Mage_Core_Controller_Front_Action
{
//默认控制器
public function indexAction()
{
echo '默认的action,如果没有指定action的话就会访问它';
}
public function sayAction()
{
echo "Hello World!";
}
}
如何访问controllers下的HelloWorldController.php呢?
#修改模块配置文件的路由规则
编辑app\etc\config.xml
<?xml version="1.0"?>
<config>
<modules>
<Nano_App>
<version>0.0.1</version>
</Nano_App>
</modules>
<frontend><!--frontend是网站前台,admin是网站后台,install是magento的安装程序-->
<routers>
<Nano_App><!--路由的标识,要唯一 -->
<use>standard</use>
<args>
<module>Nano_App</module><!--模块-->
<frontName>app</frontName><!--在url中通过app就可以访问到Nano_App-->
</args>
</Nano_App>
</routers>
</frontend>
</config>
同样,清除magento的缓存使得配置文件生效之后,我们在浏览器上请求
jim.practise.com/index.php/app/helloWorld/say
那么就会访问到HelloWorldController下的sayAction了
而请求
jim.practise.com/index.php/app/helloWorld
或
jim.practise.com/index.php/app/helloWorld/index
就会访问到HelloWorldController下的indexAction
注:本地域名需要根据本地电脑的配置进行替换,
jim.practise.com是我本地配置的域名,指向项目文件的根目录
补充:M2 的路由规则
原文讲的是怎么访问一个 Magento 1 的控制器。M2 的 URL 规则变化很大:
http://localhost/{frontName}/{controller}/{action}
其中 frontName 在 etc/frontend/routes.xml 里定义,默认是模块名转小写,不是 M1 的 module_controller_action。
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="standard">
<route id="vendor" frontName="vendor">
<module name="Vendor_Module"/>
</route>
</router>
</config>
对应的控制器文件是 Controller/Index/Index.php,类名 Vendor\Module\Controller\Index\Index,访问 /vendor/index/index。
三个必看的排错点:
- 控制器类必须继承
\Magento\Framework\App\Action\Action,否则报Class ... does not exist。 routes.xml放在etc/frontend/而不是etc/,放错位置路由就是不生效。- 改完
routes.xml要bin/magento cache:flush。
本文整理于 2017 年,2026 年 11 月补写。