Magento2.x 插件 Module(模块)开发实战

一、基本简介
1、开发的插件模块代码同一放在 : app/code/ 目录下; 
2、模块的文件命名规则: app/code/namespace/module

    a. namespace:这里我用的 Plugin 命名 
    b. module :这里我用的 Test 命名

3、测试模块目录结构如下所示:

二、测试模块实战
(一)模块声明
    1、创建 module.xml 文件, app/code/Plugin/Test/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Plugin_Test" setup_version="1.0.0" active="true" />
</config>
    a. name:表示 module 的名称 
    b. setup_version:表示 module 的版本号

    2、创建 registration.php 文件, app/code/Plugin/Test/registration.php

<?php

\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Plugin_Test',
    __DIR__
);

    3、激活模块

        a. 终端切换目录到 mangent2 项目根目录 ; 
        b. 执行 php bin/magento setup:upgrade 命令 
        b. 结果:(出现该模块证明已经被加载)

(二)路由声明
    1、前端路由    

        a. 创建前端路由时,需要新建 app/code/Plugin/Test/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 id="test" frontName="test">
            <module name="Plugin_Test" before="Magento_Core"/>
        </route>
    </router>
</config>

    b. router 标签说明:

        id = standard 表示前端路由;

    c. route 标签说明:

        id : 对于 router 的唯一标识名; 
        frontName : 前端 URL 的控制名称;

    d. module 标签说明:

        name : 声明 module 的名称; 
        before : 表示在定义 module 之前加载; 
        after : 表示在定义 moduel 之后加载;

    2、创建前端控制器

        a. 比如 我们的前端访问路由 URL 为:web.magento2.com/test/hello/word,继续创建文件(app/code/Plugin/Test/Controller/Hello/World.php)

<?php

namespace Plugin\Test\Controller\Hello;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class World extends Action
{
    /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;

    /**
     * World constructor.
     *
     * @param Context    $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(Context $context, PageFactory $resultPageFactory)     {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
        echo "Web Hello World !";
        die;
    }
}

    b. 问刚才的路由 URL,就可以看到浏览器输出内容(Web Hello World !)了。( 记得经常先执行 php bin/magento setup:upgrade 该命令。)

(三)创建 Block
    1、上面我们说了如何从控制器输出内容到页面,但是真正与浏览器页面最相关的还是由对应的Block输出数据,那么如何创建一个block呢?

        a. 我们来修改下我们控制器app/code/Silk/Test/Controller/Helo/World.php里面的内容:

<?php

namespace Plugin\Test\Controller\Hello;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\View\Result\PageFactory;

class World extends Action
{
    /** @var  \Magento\Framework\View\Result\Page */
    protected $resultPageFactory;

    /**
     * World constructor.
     *
     * @param Context    $context
     * @param PageFactory $resultPageFactory
     */
    public function __construct(Context $context, PageFactory $resultPageFactory)     {
        $this->resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }

    /**
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
        $this->_view->loadLayout();
        $this->_view->getLayout()->initMessages();
        $this->_view->renderLayout();
    }
}
    
    b. 接着创建block文件 (app/code/Plugin/Test/Index/Hello.php)

<?php

namespace Plugin\Test\Block\Index;

class Hello extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Trackingmore\Detrack\Model\UserFactory
     */
    protected $_userFactory;

    /**
     * Hello constructor.
     *
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Trackingmore\Detrack\Model\UserFactory          $userFactory
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context
        //\Plugin\Test\Model\UserFactory $userFactory
    ) {
        //$this->_userFactory = $userFactory;
        parent::__construct($context);
    }

    /**
     * @return $this
     */
    public function _prepareLayout() {
        /* case 1 获取用户模型
         * @return string 'Plugin\Test\Model\UserFactory' (length=36)
         */
//        var_dump(
//            get_class($this->_userFactory)
//        );

//        exit;

        /* case 2 
         * load ID 为 1 的 model
         */
//        $post = $this->_userFactory->create();
//        $post = $post->load(1);
//        var_dump($post);
//        die;

        /* case 3
         * use collection
         */
//         $post = $this->_userFactory->create();
//         $collection = $post->getCollection();
//         foreach ($collection as $item) {
//             var_dump($item->getData());
//         }
//         exit;
//        var_dump($this->getUserData());die;

        return parent::_prepareLayout();
    }

    /**
     * 测试输出
     */
    public function testOutputAction() {
        echo 'block function !';
    }

    /**
     * 获取用户模型数据
     *
     * @return \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
     */
    public function getUserData() {
        $post = $this->_userFactory->create();

        $collection = $post->getCollection();

        $userArr = [];
        foreach ($collection as $item) {
            $userArr[] = $item->getData();
         }
//        var_dump($userArr);

        return $userArr;
    }
}

(四)创建前台 layout 布局文件 template 模板文件
    1、布局文件的命名规则为:

        a. 这里我们的布局文件名称 test_hello_world.xml ( app/code/Plugin/Test/view/frontend/layout/test_hello_world.xml )

<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="content">
            <block class="Plugin\Test\Block\Index\Hello" name="index.hello" template="Plugin_Test::index/hello.phtml"/>
        </referenceContainer>
    </body>
</page> 

        b. 这里我们又定义了一个 hello 模板文件,继续来新建这个模板文件。

    2、创建模板文件 hello.phtml

        a. 模板文件路径:(app/code/Plugin/Test/view/frontend/templates/index/hello.phtml)

<h1> hello world !</h1>
<h2><?php $block->testOutputAction();?></h2>

    3、现在重新执行清缓存加载组件命令,并刷新浏览器访问该 web.magento2.com/test/hello/word 路由,输出结果: hello world ! block function !

(五)数据库迁移(创建表、以及加载默认数据)
    1、创建表结构 InstallSchema.php (app/code/Plugin/Test/Setup/InstallSchema.php)

<?php

namespace Plugin\Test\Setup;

use Magento\Framework\Setup\InstallSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
use Magento\Framework\DB\Ddl\Table;
use Magento\Framework\DB\Adapter\AdapterInterface;

class InstallSchema implements InstallSchemaInterface
{
    /**
     * Installs DB schema for a module
     *
     * @param SchemaSetupInterface   $setup   数据表迁移接口
     * @param ModuleContextInterface $context 上下文
     *
     * @return bool
     */
    public function install(
        SchemaSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        //获取安装器
        $installer = $setup;

        //开始数据库安装
        $installer->startSetup();

        //安装前删除该表
        $installer->getConnection()->dropTable($installer->getTable('test_users'));

        // test_users 表
        if (!$installer->tableExists('test_users')) {
            $table = $installer->getConnection()
                ->newTable($installer->getTable('test_users'))
                ->addColumn(
                    'id',
                    Table::TYPE_INTEGER,
                    null,
                    ['identity' => true, 'nullable' => false, 'primary' => true],
                    'users ID'
                )
                ->addColumn('username', Table::TYPE_TEXT, 50, ['nullable' => false])
                ->addColumn('password', Table::TYPE_TEXT, 255, ['nullable' => false])
                ->addColumn('age', Table::TYPE_INTEGER, 255, [])
                ->addColumn('address', Table::TYPE_TEXT, 255, [])
                ->setComment('users table');
            $installer->getConnection()->createTable($table);

        }

        //结束数据库安装
        $installer->endSetup();
    }

}
    2、加载默认数据 InstallData.php (app/code/Plugin/Test/Setup/InstallData.php)

<?php

namespace Plugin\Test\Setup;

use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;


class InstallData implements InstallDataInterface
{
    /**
     * 安装方法
     *
     * @param ModuleDataSetupInterface $setup   数据表迁移接口
     * @param ModuleContextInterface   $context 上下文
     *
     * @return bool
     */
    public function install(
        ModuleDataSetupInterface $setup,
        ModuleContextInterface $context
    ) {
        $data = [
            ['username' => 'zhangsan', 'password' => '123123', 'age' => '18', 'address' => 'shenzhen'],
            ['username' => 'lisi', 'password' => '456456456', 'age' => '28', 'address' => 'shanghai']
        ];
        foreach ($data as $bind) {
            $setup->getConnection()
                ->insertForce($setup->getTable('test_users'), $bind);
          }
    }

}

(六)创建模型、资源模型、集合
    1、创建用户模型 (app/code/Plugin/Test/Model/User.php)

<?php

namespace Plugin\Test\Model;

use Magento\Framework\Model\AbstractModel;

class User extends AbstractModel
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        //初始化资源模型
        $this->_init('Plugin\Test\Model\ResourceModel\User');
    }

}

    2、创建用户资源模型 (app/code/Plugin/Test/Model/ResourceModel/User.php)

<?php

namespace Plugin\Test\Model\ResourceModel;

use Magento\Framework\Model\ResourceModel\Db\AbstractDb;

class User extends AbstractDb
{
    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('test_users', 'id');
    }

}

    3、创建用户集合 (app/code/Plugin/Test/Model/ResourceModel/User/Collection.php)

<?php

namespace Plugin\Test\Model\ResourceModel\User;

use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;

class Collection extends AbstractCollection
{
    /**
     * 数据表 主键字段 ID
     *
     * @var string
     */
    protected $_idFieldName = 'id';

    /**
     * 构造方法
     *
     * @return bool
     */
    protected function _construct()
    {
        $this->_init(
            'Plugin\Test\Model\User',
            'Plugin\Test\Model\ResourceModel\User'
        );

    }

}

    4、修改 (app/code/Plugin/Test/view/frontend/template/index/hello.phtml) Block 中的代码,加载数据库中的数据到 web 端输出,如下图所示;

<h1>我是 hello world !</h1>
<h2><?php $block->testOutputAction();?></h2>
<table width="600" border="1" cellspacing="0">
    <tr>
        <th>编号</th>
        <th>姓名</th>
        <th>密码</th>
        <th>年龄</th>
        <th>地址</th>
    </tr>
<?php foreach($block->getUserData() as $key=>$val) :?>
    <tr>
        <td>00000<?php echo $val['id'];?></td>
        <td><?php echo $val['username'];?></td>
        <td><?php echo $val['password'];?></td>
        <td><?php echo $val['age'];?></td>
        <td><?php echo $val['address'];?></td>
    </tr>
<?php endforeach;?>
</table>


转发:https://blog.csdn.net/xiaolskl/article/details/78989403 

转载于:https://my.oschina.net/ganfanghua/blog/3015696

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值