The previous article in my blog explains how the reflection mechanism of PHP works, assuming that the reader is not yet clear about the reflection mechanism, it is a good choice to search under or see my blog post. Let's start by explaining how to implement the plug-in mechanism with PHP. The so-called plug-in mechanism. Is that we define an interface. That is, we define a interface, and then the third-party plug-in to implement the interface, and then we get the plug-in, to call the plugin's function, we can not know the name of the plug-in and other information, we then use the reflection mechanism to implement this function.
Because I'm just a simple demo sample. So I write the code is not long, and very easy, so, since we understand the above steps, then you can directly see the source, the gaze is quite clear. If the reader has any unclear, can tell me, I will seriously reply.
<?php/*** we define the good one interface. Called Ixin*/interface ixin{function msg ();} /*** an enthusiastic developer wrote us a plugin class */class Xin implements Ixin{function msg () {echo "Sinsing hello";}} /*** We search for the plug-in class first. and infer whether it implements the Msg method */function find () {//defines an array of descriptive narrative plugins $plugin = Array (); foreach (Get_declared_classes () as $class) {// Instantiate the class of the reflection class $reclass = new Reflectionclass ($class);//Infer whether it implements the interface ixinif ($reclass->implementsinterface (' Ixin ')) {$ Plugin[] = $reclass;}} return $plugin;} /*** we go to call the plug-in's Msg method */function Myexec () {$arr = find (); foreach (Find () as $plugin) {//infer if the plug-in has a method Msgif ($plugin Hasmethod (' msg ')) {//Get an instance of this method class $remethod = $plugin->getmethod (' msg ');//Assume it is a static method. Then the direct call is possible if ($remethod->isstatic ()) {$remethod->invoke (null);} else{//first declares an instance of the plug-in class. Then call it $pluins = $plugin->newinstance (); $remethod->invoke ($pluins);}}} /*** We just need to call this function to be able to search the full plugin itself, and run the plug-in's msg function */myexec ();
Let me analyze it, interface Ixin is the interface we define. and Class Xin is a third-party plug-in, we use find ourselves actively search for all defined classes, and then we infer that these classes who inherit from Ixin, and implement the Msg method, we have the list since, we can use the Myexec method to call them.
Do you have a clear idea? Please call 1 for clarity.
。。 O (∩_∩) o~
Follow the Sinsing with the PHP reflection mechanism to implement the plugin