This article illustrates the method of PHP using reflection to implement plug-in mechanism. Share to everyone for your reference. The implementation methods are as follows:
code is as follows: <?php
/**
* @name PHP Reflection api--The plug-in system architecture implemented using reflection technology
*/
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 (the ' path ' => '/mycoolplugin ', ' title ' => ' is a really cool article ', ' text ' => ' xxxxx xxxx '));
}
}
$menu = Computemenu ();
$articles = Computearticles ();
Print_r ($menu);
Print_r ($articles);
I hope this article will help you with your PHP program design.