浅谈ecmall插件机制

插件是独立于原系统的程序模块,目的是在不修改原程序的情况下对系统进行扩展,便于修改和管理。目前web开发中大多是使用钩子形式来定义插件, 比较典型的有
wordpress, drupal系统

ecmall的插件机制:

ecmall提供了3中扩展系统功能的方法. 挂件,模块,插件.
方便我们进行二次开发。下面我们就演示一下如何制作一个插件。
首先在 external/plugins目录下新建一个目录,命名为hello_world,然后进入该目录,新建2个文件
main.plugin.php 和 plugin.info.php。
main.plugin.php
是运行的文件,所以的操作都包含在这个文件内。plugin.info.php
是对该插件的信息,比如:插件名称,作者,功能,版本,钩子等等…下面展示出2个文件的源代码.

main.plugin.php

     
  <?php

        class Hello_worldPlugin extends BasePlugin
       
{
                function execute()
                {
               
        echo 'hello world';
                }
        }

       
?>所有的插件类都必须以插件名称(第一个字母大写) +
‘Plugin’命名,而且是继承BasePlugin类,execute是插件的入口,ecmall会在钩子处调用插件的execute函数
plugin.info.php

 
      <?php

        return array(
                'id'             
  =>        'hello_world',
                'name'                =>   
    'hello world',
                'author'        =>        'jack',
 
              'desc'                =>        'hello world',
             
  'hook'                =>        'on_run_action',
        );

     
  ?>该文件主要是对插件的描述,id 是插件的名称,必须与文件夹的名称保持一致.
name,author,desc都是可选的参数,但hook必须要填写,它告诉ecmall在什么时候执行该插件,如果不填或者填写错误,该插件将不会起到任何效果.好了,一个简单的ecmall插件就定义好了,然后我们进入后台,在’扩展’->’插件管理’->点击 hello_world
后面的开启 即可

下面我们就来具体的分析一下这个插件的工作流程.

当我们从后台开启一个插件时,ecmall会在 /data
目录下生成一个 plugins.inc.php
的文件,该文件记录了当前系统所有开启的插件信息,我们打开来看一下它的内容

<?php

return array
(
  'on_run_action' =>
  array (
    'short_store_url' =>
 
  array (
    ),
    'hello_world' =>
    array (
   
),
  ),
);

?>返回一个数组,键是hook的名称,代表什么时候执行,值是个多维的数组,代表该hook下所有需要执行的插件.
ecmall程序会用 $this->_hook(‘on_run_action’)的方式来调用插件,_hook函数定义在/includes/ecapp.base.php
文件中,下面贴出主要代码

        /* 获取可用插件列表 */
        $plugin_list =
$plugins[$event];
        if (empty($plugin_list))
        {
          
 return null;
        }
        foreach ($plugin_list as $plugin_name
=> $plugin_info)
        {
            $plugin_main_file = ROOT_PATH .
"/external/plugins/{$plugin_name}/main.plugin.php";
            if
(is_file($plugin_main_file))
            {
               
include_once($plugin_main_file);
            }
          
 $plugin_class_name = ucfirst($plugin_name) . 'Plugin';
            $plugin =
new $plugin_class_name($data, $plugin_info);
            $this->outcall =
true;

            /* 返回一个结果,若要停止当前控制器流程则会返回true */
          
 $stop_flow = $this->_run_plugin($plugin);
            $plugin =
null;
            $this->outcall = false;可以看到,ecmall 会循环 包含当前hook下的插件文件,然后
$this->run_pugin($plugin) 来执行, 而 _run_plugin
其实就是调用插件的execute函数,整个插件流程就这样串联起来

    function
_run_plugin(&$plugin)
    {
        $plugin->execute();
   
}
总结,
虽然ecmall提供的插件机制可以让我们很简单的进行扩展,但是目前系统自带的hook太少(只有5种),与wordpress的几十种来说还相差甚远,
所以很多情况下我们都不得不自己添加一些hook来应对我们的需求.

原文地址:https://www.cnblogs.com/xihong2014/p/4429038.html