zoukankan      html  css  js  c++  java
  • php hook 之简单例子

    <?php
    // 应用单例模式
    // 建立相应的 plugins 文件夹,并建立 .php 文件放在里面
    class plugin
    {
        public $actions;
        public $filters;


        private $plugin_dir;
        private static $instance;

        public static function getInstance()
        {
            if(self::$instance == null)
            {
                self::$instance = new self;
            }
            return self::$instance;
        }

        private function __construct()
        {
            $this->actions = $this->filters = array();
            $this->plugin_dir = dirname(__FILE__).'/plugins/';
        }

        public function init()
        {

            $dir_handle = opendir($this->plugin_dir);
            while($m = readdir($dir_handle))
            {
                if($m == '.' || $m == '..')
                {
                    continue;
                }else
                {
                    $n = $this->plugin_dir . $m;
                    if(is_file($n))
                    {
                        $f = $n;
                    }else
                    {
                        $f = $n . '/' . $m . '.php';
                    }
                    include($f);
                }
            }
            closedir($dir_handle);

        }

        public function do_action($action, $params = array())
        {
            $a = $this->actions[$action];
            $c = $a;
            if(is_callable($c))
            {
                call_user_func_array($c, $params);
            }

        }

        public function add_action($action, $callable)
        {
            $this->actions[$action] = $callable;
        }

        public function add_filter($filter, $callable)
        {
            $this->filters[$filter] = $callable;
        }

        public function apply_filter($filter, $params = array())
        {
            $c = $this->filters[$filter];
            if(is_callable($c))
            {
                call_user_func_array($c, $params);
            }
        }


    }



    global $pl;
    $pl = plugin::getInstance();
    $pl->init();

    $pl->add_action("tfunc", 'hook'); //引用 pugins目录中的 hook函数而已
    $pl->do_action('tfunc', array('aa', 'bb', 'cc'));
    //结果为  array(0=>'aa', 1=>'bb', 2 => 'cc') 3表示3个参数

    //其中 plugins 中的 函数为
    /*
    function hook($param = array())
    {
        $num = func_num_args();
        $str = func_get_args();
        print_r($str);
        print_r($num);
    }
    */

  • 相关阅读:
    C开发注意事项
    Teamcenter ITK
    Teamcenter SOA开发源码: 打印对象信息
    Teamcenter服务端开发环境配置
    Teamcenter中UID和对象之间相互转化
    Teamcenter 打开数据集
    Teamcenter中SOA调用user service
    63.display:none与visibility:hidden的区别?
    60.为什么要初始化CSS样式
    58.用纯CSS创建一个三角形的原理是什么?
  • 原文地址:https://www.cnblogs.com/lin3615/p/3724849.html
Copyright © 2011-2022 走看看