<?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);
}
*/