In this paper, we share the PHP reflection api--using reflection technology to implement the plug-in system architecture, for your reference, the specific content as follows
<?php/** * @name PHP Reflection api--Plug-in system architecture using reflection technology * */** * First Call the Findplugins method to get to the class that implements the interface * and then call the Reflection class method * @param $method method Name * @param $interfaceName Interface Name * @return The return result of the array method name */function compute ($method, $interfaceName) {$findPlugins = FINDP Lugins ($interfaceName); $menu = Array (); foreach ($findPlugins as $plugin) {//Here gets to all classes that implement the IPlugin interface if ($plugin->hasmethod ($method)) {//check whether a particular method in the class is defined 。 $reflectionMethod = $plugin->getmethod ($method); Gets the method in the class if ($reflectionMethod->isstatic ()) {//Determines whether its method is a static method $items = $reflectionMethod->invoke (null ); } else {$pluginInstance = $plugin->newinstance (); Creates a new instance of the class. The given parameter is passed to the class constructor. $items = $reflectionMethod->invoke ($pluginInstance); } $menu = Array_merge ($menu, Is_array ($items)? $items: [$items]); }} return $menu;} /** * First find the class implementing the IPlugin interface from a bunch of defined classes * and then store it in the array return * @param string $interfaceName * @return Array $plugins */f Unction Findplugins ($interfaceNAME) {$plugins = array (); Returns an array of the names of defined classes, foreach (Get_declared_classes () as $class) {$reflectionClass = new Reflectionclass ($class);//Get Clas The reflection object of S, including the private property method if ($reflectionClass->implementsinterface ($interfaceName)) {//check if it implements the IPlugin interface $plugins [] = $reflectionClass; Find the class that needs reflection}} return $plugins;} Interface iplugin{public static function GetName (); Define interfaces and static methods}//implement Iplugin interface class Mycoolpugin implements Iplugin {public static function GetName () {return ' Mycoolplugin '; } public Function Getmenuitems () {//Get menu item return Array (' description ' = ' mycoolplugin ', ' link ' = '/ Mycoolplugin ')); The public static function Getarticles () {//Gets the article return array (' path ' = '/mycoolplugin ', ' title ' = ' = ' This is a r eally Cool article ', ' text ' = ' xxxxxxxxx '); }} $menu = Compute (' getmenuitems ', ' Iplugin '); $articles = Compute (' getarticles ', ' Iplugin ');p rint_r ($menu); Echo < Hr> ";p rint_r ($articles); echo"
The above is the whole content of this article, I hope that everyone's learning has helped, but also hope that we support topic.alibabacloud.com.