本文实例为大家分享了 PHP反射API--利用反射技术实现的插件系统架构,供大家参考,具体内容如下
hasMethod($method)) { //检查在类中特定的方法是否被定义。
$reflectionMethod = $plugin->getMethod($method); //获取类中的方法
if ($reflectionMethod->isStatic()) { //判断其方法是否为静态方法
$items = $reflectionMethod->invoke(null);
} else {
$pluginInstance = $plugin->newInstance(); //创建类的新实例。给定参数传递给类构造函数。
$items = $reflectionMethod->invoke($pluginInstance);
}
$menu = array_merge($menu, is_array($items)?$items:[$items]);
}
}
return $menu;
}
function findPlugins($interfaceName){
$plugins = array();
//返回由已定义类的名字所组成的数组
foreach (get_declared_classes() as $class){
$reflectionClass = new ReflectionClass($class);//获得class的反射对象,包括私有的属性方法
if ($reflectionClass->implementsInterface($interfaceName)) { //检查它是否实现了Iplugin接口
$plugins[] = $reflectionClass; //找到需要反射的类
}
}
return $plugins;
}
interface Iplugin{
public static function getName(); //定义接口和静态方法
}
//实现Iplugin接口
class MycoolPugin implements Iplugin {
public static function getName(){
return 'MycoolPlugin';
}
public 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 = compute('getMenuItems','Iplugin');
$articles = compute('getArticles','Iplugin');
print_r($menu);
echo "
";
print_r($articles);
echo "
";
$name = compute('getName','Iplugin');
print_r($name);
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



