插件式的结构是 一个 很不错的结构,整个wordpress就是 一个 很不错的插件结构。 归跟到底,整个wordpress中的 代码 都是do_action,apply_fiter,在插件中是用add_action,和add_fiter来注册插件 代码 。 所以,实现一个插件结构的程序,实现这几个函数就可以了。 首先定义一个插件的目录,本段代码在plugin.php所在目录的plugins目录中,扫描其中所有的php文件,执行其中的代码完成部分插件代码的注册。 如果文件夹中包含目录,那么进入该目录,查找与该目录同名的php文件,包含执行。这样就完成了所有的插件代码注册。
<?php if(!defined('PLUGIN')) { define('PLUGIN', true); class plugin { public $actions; public $filters; private $plugin_dir; private static $instance; public static function getInstance() { if(self::$instance == NULL) { self::$instance = new plugin(); } 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); } } } }
一段包含了插件结果的代码:
<?php include 'plugin.php'; global $pl; $pl = plugin::getInstance(); $pl->init();
$pl->do_action("hello", array(0,1,2,3)); $pl->do_action("world", array(0,1,2,3)); echo "<p>___________________________________</p>"; $n = array(); $pl->apply_filter('hello',array(&$n)); echo "<p>__________________________</p>";
var_dump($n);
查看更多关于php插件方式的一个简单实现代码的详细内容...