如何在 Magento 2 中创建控制器?

第 1 步:创建 routes.xml 文件。

文件: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()方法中,我们将编写所有控制器逻辑并返回请求的响应。

第 3 步:创建布局文件

文件: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>


第 4 步:创建块文件(php)

文件:app/code/Mageplaza/HelloWorld/Block/Index.php

<?php
namespace Mageplaza\HelloWorld\Block;
class Index extends \Magento\Framework\View\Element\Template
{

}

第 5 步:创建模板文件

文件:app/code/Mageplaza/HelloWorld/view/frontend/templates/index.phtml

<h2>Welcome to Mageplaza.com</h2>

我们可以在本主题中了解更多视图:布局、块、模板





nba2k2球员数据
请先登录后发表评论
  • 最新评论
  • 总共0条评论