IOCContainer working mechanism and understanding of container and ServiceProvider

Source: Internet
Author: User
IOCContainer working mechanism and understanding of the working mechanism of container and ServiceProvider IOC Container

Perform a test:

App/Http/routes. php <? Phpclass Bar {} class Foo {public $ bar; in the construct of the public function _ construct (Bar $ bar)/Foo class, you need to input Bar $ bar, one layer after another, in general, we need to constantly new instances to solve all dependencies // but laravel will help you automatically parse and instantiate new ones. it is easy to feel that this is a great convenience. {$ This-> bar = $ bar;} Route: get ('/', function (Foo $ foo) {// this is not actually dependency injection, dependency Injection is interface-oriented. here is just something like dependency injection. this is laravel's IOC container // laravel will try to parse the semantics of Foo $ foo, the parsing is actually to find whether there is such a class or other things. if there is such a class, it will be put here // to resolve this to a Foo class dd ($ foo );});

Laravel actually borrowed php Reflection.

PHP5 adds a new feature: Reflection. This function enables phper to reverse-engineer class, interface, function, method and extension. With PHP code, you can obtain all the information of an object and interact with it.

What is reflection?

It refers to the extension analysis of PHP programs in the PHP running state, exporting or extracting detailed information about classes, methods, attributes, parameters, and so on, including comments. This kind of dynamic information and the function of dynamically calling an object is called a Reflection API. Reflection is an API used to manipulate the object-oriented model. it is very powerful and can help us build complex and scalable applications.

Let's take a look at binding.
<? Phpclass Bar {} class Foo {public $ bar; public function _ construct (Bar $ bar) {$ this-> bar = $ bar ;}} App :: bind ('foo', function () {// laravel provides the bind method to register binding, and returns an instance through the class or interface name (the closure passed together, the function is similar to the previous automatic search and resolution. // However, if bind is used, the bind method is used first, instead of automatically searching and parsing, "call here" dd ('Call here '); return new Foo (new Bar ();}) appears first ());}); route: get ('/', function (Foo $ foo) {dd ($ foo );});

The laravel document mentions a very important point: Notice that we receive the container itself as an argument to the resolver. we can then use the container to resolve sub-dependencies of the object we are building. we receive the INER and parse it as a parameter. then we can use it to parse the sub-dependency of the object we are building. It is equivalent to handing over dependencies to the container. we only need to parse the container.

Https://laravel.com/docs/5.2/container for details

Understand container and Service Provider

The service provider is used to provide a uniform binding place for related service containers. In addition, the service provider can perform initialization and startup operations. Each core component of Laravel corresponds to a service provider. in this case, the service provider is the heart of Laravel and the core of Laravel, the core component class is registered and initialized here for subsequent calls.

Castle, Butler and slaves

Once upon a time there was a castle with a big butler who managed a working slave.

Scenario 1.

The castle is running well and there are more and more guests. The Butler thinks there should be a transport in the castle to make it easier for everyone to travel. So he bought a horse and handed it to the slave and said to the Slave:

If a customer needs transportation, he will hand over the horse.

Scenario 2.

The operation of the castle is getting better and better, and the manager has a lot of money. he thinks Matthew is slow and riding quite uncomfortable. He once again told the slaves that the next time a guest needs transportation, you will go to the Mercedes-Benz 4s store on the East Road and buy a Mercedes-Benz Class c and return it to the guests.

Scenario 3.

One day, there was a foreign politician in the castle. the Mercedes-Benz was not good enough and he had to buy Rolls-Royce. The Butler said to the slaves: if this politician needs to travel, you can buy a Rolls-Royce, but no matter how many times he asks, you can only use that one, and you cannot buy another one (the car is too expensive ).

The castle corresponds to the container, the Butler is the service provider, and the horse, the Mercedes-Benz, and the Rolls-Royce are the service.

Reference link: http://jingpin.jikexueyuan.com/article/44059.html

This is an example of the service provider document on the official website.

<? Phpnamespace App \ Providers; use Riak \ Connection; use Illuminate \ Support \ ServiceProvider; class RiakServiceProvider extends ServiceProvider {/*** Register bindings in the container. ** @ return void */public function register () // The register method is unique to the service provider. the fixed syntax {$ this-> app-> singleton (Connection: class, function ($ app) {// Here we can see that this is the binding method of a INER, using the singleton method, service provider manages container return new Connection (config ('riak '));});}}

Singleton method

$ This-> app-> singleton ('foobar', function ($ app) {// The singleton method binds a class or interface name to a container, then return the same instance return new FooBar ($ app ['somethingelse']) in the subsequent call; // the class name of FooBar is bound here, then a same FooBar instance is returned here });
Then let's take a look at a FilesystemServiceProvider. php provider in the laravel project to compare it.
Vendor/laravel/framework/src/Illuminate/Filesystem/FilesystemServiceProvider. php <? Phpnamespace Illuminate \ Filesystem; use Illuminate \ Support \ ServiceProvider; class FilesystemServiceProvider extends ServiceProvider {/*** Register the service provider. ** @ return void */public function register () // There is a register method {$ this-> registerNativeFilesystem (); // A local method $ this-> registerFlysystem ();}/*** Register the native filesystem implementation. ** @ return void */protected function registerNativeFilesystem () // This is the method, which uses singleton and binds a file, but the returned FileSystem name is not the same, // singleton actually does a similar ING and binds files to the new Filesystem, when we access files, we can access new Filesystem {$ this-> app-> singleton ('files ', function () {return new Filesystem ;});} omitted ..............

As mentioned above, the service provider itself is actually equivalent to a container manager to facilitate the management of container, but there is nothing operational in itself. The core is to call the container. So I want to call back the container, because I still don't know how this container is used,

There are several ways to use INER. In other words, using it is actually to parse the name of the container to obtain information about the container.
$ FooBar = $ this-> app-> make ('foobar'); // use the make method, which belongs to the make method of the container, make accepts the parameters make (string $ abstract, array $ parameters = array (). // It is mainly used to parse the given information from the container, returns a container instance $ fooBar = $ this-> app ['foobar']; // you can use the array input method.

You can view the source code to learn about these usage methods.

Vendor/laravel/framework/src/Illuminate/Foundation/helpers. phpif (! Function_exists ('app') {/*** Get the available container instance. ** @ param string $ make * @ param array $ parameters * @ return mixed | \ Illuminate \ Foundation \ Application */function app ($ make = null, $ parameters = []) {if (is_null ($ make) {return Container: getInstance (); // A container instance will be returned} return Container: getInstance () -> make ($ make, $ parameters );}}

Reference: https://laravel.com/docs/5.2/container#resolving

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.