PHP API Reflection Instance

Source: Internet
Author: User
Tags php language

*
Reflection is an API that manipulates the meta-model of an object-oriented paradigm and is powerful in helping us to build complex, scalable applications. The purpose is to automatically load plugins, automatically generate documents, and even to augment the PHP language. The PHP reflection API consists of several classes that help us to access the program's metadata or to interact with the related annotations. With reflection we can obtain methods such as class implementations, create an instance of a class (unlike the one created with new), Invoke a method (also different from a regular call), pass a parameter, and invoke the static method of the class dynamically.
*
**
The Reflection API is a PHP built-in OOP technology extension that includes classes, exceptions, and interfaces that are used in combination to help us analyze other classes, interfaces, methods, properties, methods, and extensions. These OOP extensions are called reflections, located in the PHP source/ext/reflection directory.
You can use the reflection API to reflect the reflection API itself (which may be the initial meaning of reflection, "see Yourself" yourself):

<?phpreflection::export (New Reflectionextension (' reflection '));? >

Almost all of the reflection APIs implement the Reflector interface, and all classes that implement the interface have an export method that prints information about the parameter object.
Use Get_declared_classes () to get all the PHP built-in classes, get_declared_interfaces ();
Get_defined_functions (); Get_defined_vars (); Get_defined_constants (); Access to PHP interfaces, methods, variables, constant information.

Reflections on:

<?php//defines a custom class mytestclass{public        function TestFunc ($para 0= ' DefaultValue0 ') {            }}//next reflects it foreach ( Get_declared_classes () as $class) {    //Instantiate a reflection class    $reflectionClass = new Reflectionclass ($class);    If the class is a custom class    if ($reflectionClass->isuserdefined ()) {      //Export the class information        Reflection::export ($reflectionClass );    }}? >

How the fragment instance above looks at the basic information of the custom class.
The data describing data is called metadata, and the information obtained by reflection is metadata information, which is used to describe classes, interface methods, and so on. (Yuan---"is the original meaning, such as the meta-model is a model describing the model, such as the UML meta-model is to describe the UML structure of the model), metadata can be further divided into hard metadata (matadata) and soft meta-data (soft metadata), the former by the compiled code export, such as class name, method, parameter, etc.
The latter is an artificially added data, such as Phpdoc blocks, attributes in PHP, and so on.


Many of the business software is now based on plug-in architectures, such as Eclipse, and some of the famous Ides such as visual Studio,netbeans are plugin-based GUI applications. When a third party or this party develops the plug-in, it must import the defined related interfaces, implement these interfaces, and finally put the implemented packages in the specified directory, and the host application automatically detects all plug-in implementations at startup and loads them. It is also possible if we want to implement such an architecture ourselves.

<?php//first defines the UI interface interface IPlugin {//Gets the name of the plug-in public static function GetName ();//menu item to display function Getmenuitems ();// The article to display function getarticles ();//the Navigation bar function Getsidebars () to be displayed;} This is the implementation of the plug-in interface class Someplugin implements IPlugin {public Function Getmenuitems () {//Return menu item return null;} Public Function Getarticles () {//returns our article return null;} Public Function Getsidebars () {//We have a navigation bar return array (' Sidebaritem ');} Return plug-in name public static function GetName () {return "Someplugin";}}? >

PHP also has a solution that uses plug-ins, unlike Eclipse.
Use our plugins: 1. Use Get_declared_classes () to get all loaded classes first. 2. Traverse all classes to see if it implements our custom plug-in interface IPlugin. 3. Get all the plugin implementations. 4. Interacting with plugins in the host app

The following method helps us find all the classes that implement the plug-in interface:

function Findplugins () {$plugins = array (); foreach (Get_declared_classes () as $class) {$reflectionClass = new Reflectionclass ($class);//Determines whether a class implements the IPlugin interface if ($reflectionClass->implementsinterface (' IPlugin ')) {$plugins [ ] = $reflectionClass;}} return $plugins;}

Notice that all plug-in implementations are returned as instances of the reflection class, not the class name itself, or an instance of the class. Because if you use reflection to invoke a method, you also need some conditional judgment.
Determines whether a class implements a method that uses the Hasmethod () method of a reflection class.
Next we put all the plugin menu items on a menu.

function Integratepluginmenus () {$menu = array ();//traverse all plug-ins to implement foreach (Findplugins () as $plugin) {// Determine if the plug-in implements the Getmenuitems method if ($plugin->hasmethod (' Getmenuitems ')) {/* Instantiates a method instance (note that when you see classes and methods as concepts, they can have instances, like "people" The same concept), the method returns the instance of Reflectionmethod */$reflectionMethod = $plugin->getmethod (' getmenuitems ');//If the method is static if ($ Reflectionmethod->isstatic ()) {//Call the static method, note that the parameter is null instead of a reflection class instance $items = $reflectionMethod->invoke (null);} else {/ /If the method is not static, instantiate an instance of the class represented by the instance of the Reflection class. $pluginInstance = $plugin->newinstance ();//Use the Reflection API to invoke a method where the argument is an object reference instantiated by Reflection $items = $reflectionMethod->invoke ( $pluginInstance);} Merge all plug-in menu items as a menu. $menu = Array_merge ($menu, $items);}} return $menu;}

Method Invocation of the reflection method instance that is used primarily here:
Public mixed Invoke (Stdclass object, mixed args=null);
Be sure to make sure that our regular method calls are in this form: $objRef->somemethod ($argList ...);
Because reflection is used, when you want to invoke a method, the form becomes:
$reflectionMethodRef->invoke ($reflectionClassRef, $argList ...);
If you use reflection to invoke a method, we must instantiate an instance of the reflection method, and if the instance method has a reference to an instance, you may need to pass the necessary arguments as well. When a static method is called, NULL is passed explicitly as the first parameter. The
has similar processing logic for other methods implemented by the plug-in class, which is no longer covered.
Here is one of my simple tests:

<?php/*** defines a plug-in interface * */interface iplugin{/** * getsidebars () * * @return return to the side navigation bar */Public functi    On Getsidebars (); /** * GETNAME () * * @return Return class name */public static function GetName ();} /* Below is the implementation of the plug-in, in fact, should be placed in a different file, or even a different package */class Myplugin implements iplugin{Public Function Getsidebars () {//construct their own                                Navigation bar $sideBars = ' <div><ul > <li><a href= ' >m1</a>                              </li> <li><a href= "" >m2</a> </li>        </ul> </div> ';    return $sideBars;    } public static function GetName () {return ' myplugin '; }}//the second plug-in implementation, class MYPLUGIN2 implements iplugin{Public Function Getsidebars () {//constructs its own navigation bar $sideBars = ' <div><ul > <li><a href= ' >mm1</a> </li> <li><a href= "" >mm2</a> </li>        </ul> </div> ';    return $sideBars;    } public static function GetName () {return ' MyPlugIn2 ';     }}//uses the plug-in class hostapp{public Function Initall () in the host program () {//Initialize each part of echo "yiqing95.";    $this->renderall ();        }//Render GUI grid part function Renderall () {$rsltSidebars = "<table>"; foreach ($this->integratesidebarsofplugin () as $sidebarItem) {$rsltSidebars. = "<tr><td> $sidebarIte        M</td></tr> ";                } $rsltSidebars. = "</table>";    Echo $rsltSidebars;        }/* Load all plug-in implementations: */protected function Findplugins () {$plugins = array ();            foreach (Get_declared_classes () as $class) {$reflectionClass = new Reflectionclass ($class); if ($reflectionClass->implementsinterface (' IPlugin ')) {$plugins [] = $reflectionClass;    }} return $plugins;        }/** Load assembly all plug-ins implement ***/protected function Integratesidebarsofplugin () {$sidebars = array (); foreach ($this->findplugins () as $plugin) {if ($plugin->hasmethod (' Getsidebars ')) {$REFL                Ectionmethod = $plugin->getmethod (' Getsidebars ');                if ($reflectionMethod->isstatic ()) {$items = $reflectionMethod->invoke (null);                    } else {$pluginInstance = $plugin->newinstance ();                $items = $reflectionMethod->invoke ($pluginInstance);            }}//$sidebars = Array_merge ($sidebars, $items);        $sidebars []= $items;    } return $sidebars; }}//Run Program: $entryClass =new Hostapp (); $entryClass->initall (); >

****
xxxx
$reflectionClass = new Reflectionclass ("IPlugIn");
Echo $reflectionClass-getdoccomment ();
This code can help us get the documentation comments for the class, and once we get the comments on the class we can extend our class functionality, such as getting a comment first, then parsing the comment using DocBlock tokenizer "pecl extension", or using the Tokenizer class or using a regular expression, a string function to parse the comment document, you can include anything in the note, including instructions, which can be used to determine the instructions or data passed by the comment before using the reflection call:
<?php
"Analyze related annotation data"
Analyse ($reflectionClass-getdoccomment ());//analyse is defined by himself!!!
Execute the method based on the results of the analysis, or pass parameters, etc.
if (xxxx) {
$reflectionMethod->invoke ($pluginInstance);
}
?>
Because annotations are strings, you can use any string parsing technique, extract useful information, and then invoke methods based on that information, which means that the logic of the program can be determined not only by the method, but also by the annotations (provided that you use reflection and that the annotation format is strictly required).

The reflection API is as extensible as other classes, so we can add our own functionality to these APIs. Combine custom comment markers. It's the stuff that starts with @, labeled (called Annotation in Java), and. NET is called an attribute attribute (or attribute). Then extend the reflection class, and you'll be able to implement powerful extension capabilities.
It is worth mentioning that the factory method design pattern (one of the Gof), also often uses reflection to instantiate the object, the following is the pseudo code of the sample nature:

Class xxxfactory{function getinstance ($className) {   $reflectionClass =new reflectionclass ($className);   return $reflectionClass->newinstance ();    
Reprint: http://blog.csdn.net/siren0203/article/details/5994571

PHP API Reflection Instance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.