PHP反射API实现插件机制
时间:2010-10-17 来源:flandycheng
<?php
interface Iplugin{
public static function getName();
}
class ContactPlugin implements Iplugin{
public static function getName(){
return __class__;
}
public static function getMenu(){
return array(
array('Contact','/contact/index.php/')
);
}
}
class HelpPlugin implements Iplugin{
public static function getName(){
return __class__;
}
public function getMenu(){
return array(
array('Help','/help/index.php/')
);
}
}
function findPlugins(){
$plugins = array();
$all_classes = get_declared_classes();
foreach($all_classes as $class){
$reflection_class = new ReflectionClass($class);
if($reflection_class->isUserDefined()&&$reflection_class->implementsInterface('Iplugin'))
$plugins[] = $reflection_class;
}
return $plugins;
}
function findMenus(){
$plugins = findPlugins();
$menus = array();
foreach($plugins as $eachPlugin){
if($eachPlugin->hasMethod('getMenu')){
$reflect_methond = $eachPlugin->getMethod('getMenu');
if($reflect_methond->isStatic()){
$method = $reflect_methond->invoke(null);
}else{
$plugin_instance = $eachPlugin->newInstance();
$method = $reflect_methond->invoke($plugin_instance);
}
$menus[] = $method;
}
}
return $menus;
}
$all_plugins = findPlugins();
print_r($all_plugins);
$all_menus = findMenus();
print_r($all_menus);
interface Iplugin{
public static function getName();
}
class ContactPlugin implements Iplugin{
public static function getName(){
return __class__;
}
public static function getMenu(){
return array(
array('Contact','/contact/index.php/')
);
}
}
class HelpPlugin implements Iplugin{
public static function getName(){
return __class__;
}
public function getMenu(){
return array(
array('Help','/help/index.php/')
);
}
}
function findPlugins(){
$plugins = array();
$all_classes = get_declared_classes();
foreach($all_classes as $class){
$reflection_class = new ReflectionClass($class);
if($reflection_class->isUserDefined()&&$reflection_class->implementsInterface('Iplugin'))
$plugins[] = $reflection_class;
}
return $plugins;
}
function findMenus(){
$plugins = findPlugins();
$menus = array();
foreach($plugins as $eachPlugin){
if($eachPlugin->hasMethod('getMenu')){
$reflect_methond = $eachPlugin->getMethod('getMenu');
if($reflect_methond->isStatic()){
$method = $reflect_methond->invoke(null);
}else{
$plugin_instance = $eachPlugin->newInstance();
$method = $reflect_methond->invoke($plugin_instance);
}
$menus[] = $method;
}
}
return $menus;
}
$all_plugins = findPlugins();
print_r($all_plugins);
$all_menus = findMenus();
print_r($all_menus);
相关阅读 更多 +