How can we easily understand the reflection and dependency injection concepts in php?

Source: Internet
Author: User
Thank you for your advice. thank you.

Reply content:

Thank you for your advice.

It's not necessary to know. really, don't tease you.
Unless you develop frameworks like ZendFramework, ThinkPHP, and CakePHP, there is almost no chance to use them.
This is a very underlying thing, especially the application scenario of dependency injection, which is to assist Development. the selected framework supports dependency injection and does not need to be implemented by itself. Reflection is similar. in business logic, I have never encountered a problem that must be solved by reflection. it is also used by the framework.

Oh, wrong. you only need to know the concept.
Reflection obtains information through reverse analysis of object instances. for example, reflection-based PHPDocument files of corresponding classes are automatically generated based on object instances.
Dependency injection is used to automatically analyze the parameters required for constructing objects and calling methods, and automatically inject the parameters. Generally, instances of such objects need to be obtained through specific methods, but it is difficult to construct them through simple new.

Reflection can dynamically obtain class information and make modifications. For example, some magic methods _ FUNCTION __,__ METHOD __. For more information, you can use reflectionClass, which is obtained by the reflection class.
Dependency injection is also called control inversion. Time for code demonstration

Unclear, mainly some magic methods of the class
You can exploit Baidu's php Serialization vulnerability

1. First of all, let's explain the familiar "Dependency Injection". Dependency Injection refers to one-time transmission of dependent objects through Parameters, rather than displaying new during use. Su Zi:

// This is dependency injection... Class Bar {} class Foo {protected $ bar; public function _ construct (Bar $ bar) {$ this-> bar = $ bar;} public function getBar () {return $ this-> bar ;}}$ bar = new Bar (); $ foo = new Foo ($ bar ); // inject the $ Bar object of the bar class into it as a parameter

2 extension:
// Dependent class Human
Abstract class Human
{
}

// Inherit Woman of dependent class Human
Class Woman extends Human
{
}

Class Man extends Human
{

protected $wife;public function setWife(Human $human){   $this->wife = $human;}

}

$ Man = new Man ();
$ Man-> setWife (new Woman ());

Conclusion: when the class declared before dependency injection, this class can be any class that inherits the dependent class (the same interface)

Reflection is a reverse ing that is used to obtain information about classes (not just classes). For example, you want to know which methods a class contains, what parameters are required for these methods, and what type each parameter is.

Dependency Injection must be implemented using reflection, for example:

Class A {protected $ B; public function _ constrcut (B $ B) {$ this-> B = $ B ;}} // when an instance of A is generated by controlling the reverse container, through reflection, we will find that the constructor of A requires A Class B instance. // then, the constructor of Class a is automatically injected with Class B instances $ A = IoC: make (:: class );

Reflection is also useful. for example, a series of assertions are made in unit tests, and some private attributes are obtained and judged, as well as PHPDocument generation (because reflection can obtain methods and class annotations)

This feature is clearly required for control inversion and dependency injection.

For details about dependency injection, refer to my blog post. Although this article is intended for the Laravel framework, it is also universal (Laravel uses a wide range of design patterns and is not abused, just right, suitable for learning ):

Https://www.insp.top/article/learn-laravel-container

Dependency Injection dynamically loads and instantiates class objects. It is generally used to read configuration files and load them as needed.

In addition to this, reflection can also achieve dynamic access to object members. Php is a more powerful scripting language. It can also add new members to an object by modifying the association table in the object.

Ie8 with e. cancelBubble = true
Use e. stopPropagation ()

Dependency Injection. in my understanding, objects are loaded into the class constructor. in order to decouple them, we usually choose the interface method to assemble them in the configured on-demand loading into the main class, multiple functions
Reflection is used to retrieve the attributes and methods in the class.

Recommend an address for you, Baidu.

Https://3v4l.org/1OVmo

Class Request {public function hello () {return 'hello';} class App {public function name () {return 'The app';} public function response (Request $ req, app $ app) {return $ req-> hello (). $ app-> name () ;}// dependency lookup or automatic dependency injection $ c ['app'] = new App; $ c ['request'] = new Request; $ r = new ReflectionMethod ('app', 'response'); $ params = $ r-> getParameters (); $ params = array_map (function ($ p) use ($ c) {$ className = $ P-> getClass ()-> name; return $ c [$ className]? Null ;}, $ params); $ res = $ r-> invokeArgs ($ c ['app'], $ params); // manual dependency injection $ App = new app; $ req = new Request; $ res = $ app-> response ($ req, $ app );

The name is actually quite simple.
Reflection is actually to get the class information (think of the class as an object, and then get some attributes of this object through the reflection class). For example, you have a class for sending emails.


  setHandle($mail);    }        public function setHandle(Mailer $mail)    {         $this->mail = $mail;    }}

For example:
I want to know the methods of this class, so I can:


  getMethods();

I want to know the parameters to be passed by the constructor of this class.


  getParameters();

In a word, reflection is used to obtain class information.

Control inversion is also easy to understand, but you must first understand that control inversion and dependency injection are not the same thing.
Control inversion is a purpose, and one of the implementation methods is dependency injection.
The so-called dependency injection is not a new class, but a dedicated class that solves the class dependency problem, for example, the preceding MailerService class depends on the Mailer class. this special class gets the parameters required by the constructor of the MailerService class through reflection. the required parameters are also called dependencies and then the dependencies are resolved. this is called dependency injection. generally, dependency injection is used to reverse control. the specialized class above is also called a service container.

Related Article

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.