本示例中命名空间为:Magento,模块名为:Hello,示例链接为http://localhost/magento20/hello/index/index。

1、创建app/code/Magento/Hello/etc/module.xml文件来声明模块

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
   <module name="Magento_Hello" schema_version="0.0.1"/>
</config>

2、创建控制器和动作:

创建app/code/Magento/Hello/Controller/Index/Index.php,其中Index扮演控制器的角色,Index.php是动作。Index.php中执行的方法是execute()。

namespace Magento\Hello\Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
  public function execute()
{
     $this->_view->loadLayout();
       $this->_view->getLayout()->initMessages();
    $this->_view->renderLayout();
}
}

创建一个块:app/code/Magento/Hello/Block/Hello.php

namespace Magento\Hello\Block;
class Hello extends \Magento\Framework\View\Element\Template
{
public function _prepareLayout()
{
    return parent::_prepareLayout();
}
}

写配置文件/app/code/Magento/Hello/etc/frontend/routes.xml

在Magento2中config.xml 只配置默认<default>标签中的配置值。前端路由的信息会在Magento/Hello/etc/frontend/routes.xml中(后台也是类似的)。前端事件会被声明在Magento/Hello/ect/frontend/events.xml(后台类似)。我们这里只是一个简单的示例,只在Magento/Hello/etc/frontend/routes.xml中声明路由。

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
<router id="standard">
    <route id="hello" frontName="hello">
        <module name="Magento_Hello" />
    </route>
</router>
</config>

3、创建前端模板

这一步中布局的名字很重要,它将被命名在结构后:router name_controller namer_action name(路由器名_控制器名_动作名)。

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">
<body>
    <referenceContainer name="content">
        <block class="Magento\Hello\Block\Hello" name="hello" template="success.phtml">
        </block>
    </referenceContainer>
</body>
</page>

接着,我们创建布局文件中调用的success.phtml文件。

<?php echo ‘Successful! This is a simple module in Magento 2.0′; ?>

4、打开app/etc/config.xml,在‘module’数组里添加元素‘Magento_Hello’ => 1,

最后访问http://localhost/magento20/hello/index/index,查看结果。

360magento提供专业的基于magento系统的电商网站开发服务,如有需求或相关咨询,请与我们联系