文件:app/code/Mageplaza/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 frontName="helloworld" id="helloworld"> <module name="Mageplaza_HelloWorld"/> </route> </router> </config>
文件:app/code/Mageplaza/HelloWorld/Controller/Index/Index.php
<?phpnamespace Mageplaza\HelloWorld\Controller\Index;class Index 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()
{
return $this->_pageFactory->create();
}}如您所见,所有控制器都必须是\Magento\Framework\App\Action\Action具有调度方法的扩展类,该方法将调用execute()动作类中的方法。在此execute()方法中,我们将编写所有控制器逻辑并返回请求的响应。
文件:app/code/Mageplaza/HelloWorld/view/frontend/layout/helloworld_index_index.xml
<?xml version="1.0"?><page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"> <referenceContainer name="content"> <block class="Mageplaza\HelloWorld\Block\Index" name="helloworld_index_index" template="Mageplaza_HelloWorld::index.phtml" /> </referenceContainer></page>
文件:app/code/Mageplaza/HelloWorld/Block/Index.php
<?php
namespace Mageplaza\HelloWorld\Block;
class Index extends \Magento\Framework\View\Element\Template
{
}文件:app/code/Mageplaza/HelloWorld/view/frontend/templates/index.phtml
<h2>Welcome to Mageplaza.com</h2>
我们可以在本主题中了解更多视图:布局、块、模板。