美文网首页
怎样创建控制器

怎样创建控制器

作者: 搬砖家 | 来源:发表于2018-06-06 14:35 被阅读22次

在MVC中,控制器(Controller)的作用通常是在获取模型(Model)中数据并交给视图(View)去显示,它的功能是接收到的请求、处理和呈现页面。那在Magento2中我们应该如何去写呢?

在Magento 2中,控制器在模块的Controller文件夹中,里面有一个或多个文件,每个文件都包含execute()方法,有两种不同的控制器,分别是前端控制器和后端控制器,它们在工作流程上通常是相似的,但有点不同的是,后端控制器中有一个检查权限方法,它调用form key。

控制器是怎么工作的?

它接收来自用户(浏览器或命令行)的请求,例如:

http://example.com/route_name/controller/action
  • route_name 路由名称,在routes.xml中定义
  • controller 控制器目录的名称
  • action 动作名称,处理请求执行方法的类

其中一个重要的Magento系统是前端控制器 (Magento\Framework\App\FrontController),它总是接收请求然后通过路由转发到控制器,动作route_name让我们以一个路由请求的例子为例:

foreach ($this->_routerList as $router) {
   try {
      $actionInstance = $router->match($request);
   …
}

如果找到对应的控制器和操作,execute()方法将被执行。

如何创建控制器?

创建控制器,我们需要在模块下面创建一个Controller文件夹,并在其中声明一个操作类。例如,我们创建一个index controller和一个index模块的操作,Mageplaza_HelloWorld:

第1步:创建routes.xml文件

文件路径 :app/code/Max/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="Max_HelloWorld"/>
        </route>
    </router>
</config>

如果已经创建了这个文件,则可以忽略此步骤。

步骤2:创建控制器文件

文件路径:app/code/Max/HelloWorld/Controller/Index/Index.php
代码如下:

<?php
namespace Max\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/Max/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="Max\HelloWorld\Block\Index" name="helloworld_index_index" template="Max_HelloWorld::index.phtml" />
    </referenceContainer>
</page>

步骤4:创建块文件

文件路径:app/code/Max/HelloWorld/Block/Index.php
代码如下:

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

}

步骤5:创建模板文件

文件路径:app/code/Max/HelloWorld/view/frontend/templates/index.phtml

<h2>Welcome to Magento</h2>

步骤6:刷新Magento缓存

bin/magento cache:clear

步骤7:运行测试

让我们打开浏览器并导航到

http://example.com/helloworld/index/indexhttp://example.com/helloworld/

image.png

相关文章

网友评论

      本文标题:怎样创建控制器

      本文链接:https://www.haomeiwen.com/subject/cnybsftx.html