本篇文章将介绍如何创建一个输出 hello world
的简单模块。
在 Magento 2 中,模块存在于 app/code
目录下,格式如下
app/code/<Vendor>/<ModuleName>
。
第一步:创建模块所需的目录
我们将使用 ThankIT
作为 Vendor name ,HelloWorld
作为 ModuleName ,所以我们现在创建文件目录 app/code/ThankIT/HelloWorld
第二步:创建 module.xml 声明该模块
在上面创建的目录下,创建 etc
目录,在 etc
下创建 module.xml
<!-- File: app/code/ThankIT/HelloWorld/etc/module.xml -->
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="ThankIT_HelloWorld" setup_version="1.0.0" />
</config>
在该配置文件中,我们注册了一个模块名称为 ThankIT_HelloWorld
的模块,它的版本是 1.0.0
第三步:创建 registration.php 注册模块
Magento 2 中的所有模块都必须通过 magento 的 ComponentRegistrar 类进行注册。
#File: app/code/ThankIT/HelloWorld/registration.php
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'ThankIT_HelloWorld',
__DIR__
);
第四步:Enable 该模块
上面步骤做完后,我们就已经创建好了一个空模块,下面输入以下命令行,看看我们的模块是否已经注册好了。
php bin/magento module:status
你会看到
List of disabled modules:
ThankIT_HelloWorld
这代表,模块已经被检测到,但 disabled 状态,下面启用它
php bin/magento module:enable ThankIT_HelloWorld
如果看到以下信息,表明模块已经成功启用了
The following modules has been enabled:
- ThankIT_HelloWorld
这是你第一次启用该模块,magento 需要检查和升级模块的数据库记录,运行以下命令行
php bin/magento setup:upgrade
现在我们进入后台,在 Stores -> Configuration -> Advanced -> Advanced
下我们可以看到该模块了
第五步:为模块创建路由
Magento 系统中,请求 URL 是如下格式
http://example.com/<router_name>/<controller_name>/<action_name>
路由用来分配 URL 给对应的 controller (控制器)和 action 。在该模块中,我们给前端创建一个路由,所以创建下面的文件
<!-- File: app/code/ThankIT/HelloWorld/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="helloworld" frontName="helloworld">
<module name="ThankIT_HelloWorld" />
</route>
</router>
</config>
定义好路由后,我们的模块 URL 路径变成 http://example.com/helloworld/*
第六步:创建 controller 和 action
在该步骤中,我们将创建 controller 和 action 来输出 Hello World
。假设我们的 URL 是 http://example.com/helloworld/index/display
所以我们将创建如下文件
#File: app/code/Mageplaza/HelloWorld/Controller/Index/Display.php
<?php
namespace ThankIT\HelloWorld\Controller\Index;
class Display extends \Magento\Framework\App\Action\Action
{
public function __construct(
\Magento\Framework\App\Action\Context $context
){
return parent::__construct($context);
}
public function execute()
{
echo 'Hello World';
exit;
}
}
如果打开 http://example.com/helloworld/index/display
就会看到输出 Hello World
字符串。
如果出现 404 请清空缓存 php bin/magento cache:clean
参考文档
Magento 2 Module Development – Magento 2 Hello World Simple Module
害死我了
大哥 mudule.xml =》 module.xml
Pisces Post author
“在 etc 下创建 mudule.xml” 已更正为 module.xml 。