magento 2模块开发实例helloworld模块

409 查看

1、在app/etc/config.php中添加自定义的模块(magento1声明模块是在app/etc/modules):

 'Silk_Helloworld' =>1,

值为1,开启模块,类似true,0关闭模块
2、创建module.xml:app/code/Silk/Helloworld/etc/module.xml

 <?xml version="1.0" encoding="UTF-8" ?>
  <module name="Silk_Helloworld" setup_version="2.0.0" /> 

3、创建前段控制器:app/code/Silk/Helloworld/ect/fronted/routers.xml

<?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="helloworld" frontName="helloworld">
            <module name="Silk_Helloworld" />
        </route>
    </router>
</config>

4、创建一个控制器:appcodeSilkhelloworldControllerIndexindex.php

namespace Silk\Helloworld\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
       $this->getResponse()->appendBody('HELLO WORLD');
    }
}

5、创建文件app/code/Silk/Helloworld/registration.php:

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Silk_Helloworld',/*namespace/module*/
    __DIR__
);

6、创建文件app/code/Silk/Helloworld/composer.json:
{

 "name": "silk/helloworld",/*namespace/module*/
  "description": "silk",/*namespace*/
  "require": {
    "php": "~5.5.0|~5.6.0|~7.0.0",
    "magento/framework": "100.0.*",
    "magento/module-ui": "100.0.*",
    "magento/module-config": "100.0.*",
    "magento/module-contact": "100.0.*"
  },
  "type": "magento2-module",
  "version": "100.0.0",
  "license": [
    "OSL-3.0",
    "AFL-3.0"
  ],
  "extra": {
    "map": [
      [
        "*",
        "Silk/Hellworld"/*namespace/module*/
      ]
    ]
  },
  "autoload": {
    "files": [ "registration.php" ],
    "psr-4": {
      "silk\\helloworld\\": ""/*namespace/module*/
    }
  }
}

7、执行命令:php bin/magento setup:upgrade
xampp环境使用该命令方法:
(1)、打开shell,输入cd htdocsmagento,回车
(2)、输入上面的命令,等待一会即可.
linux环境:
php bin/magento setup:upgrade
8、在浏览器中输入silk.magento2.cn/helloworld.显示:

helloworld模块创建成功了。
9、登录到后台,可以查看新建的helloworld模块: Stores > Configuration > Advanced > Advanced.