php利用反射实现插件机制功能实例

前端之家收集整理的这篇文章主要介绍了php利用反射实现插件机制功能实例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP利用反射实现插件机制的代码感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

/**
 * PHP利用反射实现插件机制的代码
 *
 * @param 
 * @arrange 512-笔记网: www.512Pic.com
 **/  
interface Iplugin{    
	public static function getName();    
}    
function findPlugins(){    
	$plugins = array();    
	foreach (get_declared_classes() as $class){    
		$reflectionClass = new ReflectionClass($class);    
		if ($reflectionClass->implementsInterface('Iplugin')) {    
			$plugins[] = $reflectionClass;    
		}    
	}    
	return $plugins;    
}    
function computeMenu(){    
	$menu = array();    
	foreach (findPlugins() as $plugin){    
		if ($plugin->hasMethod('getMenuItems')) {    
			$reflectionMethod = $plugin->getMethod('getMenuItems');    
			if ($reflectionMethod->isStatic()) {    
				$items = $reflectionMethod->invoke(null);    
			} else {    
				$pluginInstance = $plugin->newInstance();    
				$items = $reflectionMethod->invoke($pluginInstance);    
			}    
			$menu = array_merge($menu,$items);    
		}    
	}    
	return $menu;    
}    
function computeArticles(){    
	$articles = array();    
	foreach (findPlugins() as $plugin){    
		if ($plugin->hasMethod('getArticles')) {    
			$reflectionMethod = $plugin->getMethod('getArticles');    
			if ($reflectionMethod->isStatic()) {    
				$items = $reflectionMethod->invoke(null);    
			} else {    
				$pluginInstance = $plugin->newInstance();    
				$items = $reflectionMethod->invoke($pluginInstance);    
			}    
			$articles = array_merge($articles,$items);    
		}    
	}    
	return $articles;    
}   
class MycoolPugin implements Iplugin {    
	public static function getName(){    
		return 'MycoolPlugin';    
	}    
	public static function getMenuItems(){    
		return array(array('description'=>'MycoolPlugin','link'=>'/MyCoolPlugin'));    
	}    
	public static function getArticles(){    
		return array(array('path'=>'/MycoolPlugin','title'=>'This is a really cool article','text'=> 'xxxxxxxxx' ));    
	}    
}
$menu = computeMenu();    
$articles    = computeArticles();    
print_r($menu);    
print_r($articles);   
/***   来自编程之家 jb51.cc(jb51.cc)   ***/
原文链接:https://www.f2er.com/php/528274.html

猜你在找的PHP相关文章