首先创建一个名为 Hello_World 的模块。
定义路由器:
在 app/code/Hello/World/etc/frontend/ 目录下创建 routes.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"> <!-- standard or admin -->
<route id="helloworld" frontName="helloworld">
<module name="Hello_World"/>
</route>
</router>
</config>
上述的路由定义文件,会将 URL显示为 http://<yourhost.com>/helloworld/* 。
然后我们接下来创建 Controller 和 Action 。
创建 Controller 和 Action:
我们需要创建如下目录和文件:
app/code/Hello/World/Controller/Index/Test.php
Magento的Controller存放在相应模块下的Controller目录下。Controller目录下的目录的名称就是Controller的名称。Controller目录下的目录内的文件就是Action。Controller和Action必须首字母大写。
然后将如下内容添加到 Test.php 中:
<?php
namespace Hello\World\Controller\Index;
class Test extends \Magento\Framework\App\Action\Action
{
protected $_pageFactory;
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\View\Result\PageFactory $pageFactory)
{
$this->_pageFactory = $pageFactory;
return parent::__construct($context);
}
public function execute()
{
echo "Hello World";
exit;
}
}
运行 php bin/magento cache:cache清除缓存。
然后使用下面网址调用上述 Controller 和 Action:
http://<yourhost.com>/helloworld/index/test
完成上述所有步骤后,打开上面的 URL 后,Hello World 应该在浏览器中显示出来。