Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the implementation principle of laravel service container?

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Network Security >

Share

Shulou(Shulou.com)06/01 Report--

What is the implementation principle of the laravel service container? many novices are not very clear about it. In order to help you solve this problem, the following editor will explain it in detail. People with this need can come and learn. I hope you can get something.

What is a service container?

The service container is a tool for managing class dependencies and running dependency injection. In the Laravel framework, service containers are used to implement * * control inversion * * and * * dependency injection * *.

What are inversion of Control (IoC) and dependency injection (DI)

IoC means transferring the control over the creation of an object. In the past, the initiative and timing of creating an object was controlled by yourself, but now this power is transferred to a third party, that is, a container in Laravel.

Dependency injection (DI) is to help the container to dynamically provide dependency resources for objects during operation.

The concept is easy and not easy to understand. Take a chestnut:

/ We build a human class and a dog class class People {public $dog = null; public function _ construct () {$this- > dog = new Dog ();} public function putDog () {return $this- > dog- > dogCall ();}} class Dog {public function dogCall () {return 'barking';}} ```this man is walking his dog when he suddenly meets a bitter enemy, so he sets the dog to bite.

$people = new People ()

$people- > putDog ()

In this operation, the people class needs to rely on the Dog class to execute the method putDog (). Generally, we use the constructor to add this Dog dependency in people as above. This is what happens if you use control to reverse dependency injection

Class People

{

Public $dog = null

Public function _ construct (Dog $Dog) {$this- > dog = $dog;} public function putDog () {return $this- > dog- > dogCall ();}

}

The People class declares the dependent classes it needs by constructing parameters, which are automatically injected by the container. In this way, the effective decoupling of the program is realized, and the benefit is not to be said here. # # implementation of Laravel container dependency injection # what you need to know about the implementation principle: > closure (anonymous function): anonymous function (Anonymous functions), also known as closure function (closures), allows temporary creation of a function without a specified name > reflection: PHP 5 or above has a complete reflection API, adding the ability to reverse engineer classes, interfaces, functions, methods and extensions. In addition, reflection API provides methods to extract documentation comments from functions, classes, and methods. # understand the basic use of closures and reflections. Let's take a look at how containers are implemented in Laravel. The following code is my simplified core version of the laravel framework container code:

Lass Container

{

/ * *

* Container binding, which is used to install the provided instance or provide the callback function of the instance

* @ var array

, /

Public $building = []

/ * Register a binding to the container * / public function bind ($abstract, $concrete = null, $shared = false) {if (is_null ($concrete)) {$concrete = $abstract;} if (! $concrete instanceOf Closure) {$concrete = $this- > getClosure ($abstract, $concrete);} $this- > building [$abstract] = compact ("concrete", "shared") } / / register a shared binding singleton public function singleton ($abstract, $concrete, $shared = true) {$this- > bind ($abstract, $concrete, $shared);} / * the callback closure * * @ param $abstract * @ param $concrete * @ return Closure * / public function getClosure ($abstract, $concrete) {return function ($c) use ($abstract, $concrete) {$method = ($abstract = $concrete)? 'build':' make'; return $c-> $method ($concrete);};} / * generate instance * / public function make ($abstract) {$concrete = $this- > getConcrete ($abstract); if ($this- > isBuildable ($concrete, $abstract)) {$object = $this- > build ($concrete);} else {$object = $this- > make ($concrete);} return $object } / * get the bound callback function * / public function getConcrete ($abstract) {if (! Isset ($this- > building [$abstract]) {return $abstract;} return $this- > building [$abstract] ['concrete'];} / * determine whether a service entity can be created * / public function isBuildable ($concrete, $abstract) {return $concrete = = $abstract | | $concrete instanceof Closure;} / * instance specific object * / public function build ($concrete) {if ($concrete instanceof Closure) {return $concrete ($this) } / / create reflection object $reflector = new ReflectionClass ($concrete); if (! $reflector- > isInstantiable ()) {/ / throw exception throw new\ Exception ('cannot be instantiated');} $constructor = $reflector- > getConstructor (); if (is_null ($constructor)) {return new $concrete;} $dependencies = $constructor- > getParameters (); $instance = $this- > getDependencies ($dependencies); return $reflector- > newInstanceArgs ($instance) } / / resolve parameter dependency public function getDependencies (array $dependencies) {$results = []; foreach ($dependencies as $dependency) {$results [] = is_null ($dependency- > getClass ())? $this- > resolvedNonClass ($dependency): $this- > resolvedClass ($dependency);} return $results } / / resolve an untyped dependency public function resolvedNonClass (ReflectionParameter $parameter) {if ($parameter- > isDefaultValueAvailable ()) {return $parameter- > getDefaultValue ();} throw new\ Exception ('error');} / resolve dependency public function resolvedClass (ReflectionParameter $parameter) {return $this- > make ($parameter- > getClass ()-> name);}

}

`

Workflow of the container

Then follow the example of walking the dog above:

/ / instantiate the container class $app = new Container (); / / fill the container with Dog $app- > bind ('Dog','App\ Dog'); / / fill the container with People $app- > bind (' People', 'App\ People'); / / instantiate the class through dependency injection through the container; $people = $app- > make (' People'); / / call the method echo $people- > putDog ()

In the above example, we first instantiate the container class, and then use the bind () method to bind the interface and generate the corresponding instance's closure function. Then use the make () function to generate an instance object. In make (), isBuildable ($concrete, $abstract) is called to determine whether a given service entity ($concrete parameter) can be created. The build ($concrete) function is called as soon as it can be created, and the build ($concrete) function determines whether the passed parameter is a * * closure or a specific class name * *. If it is a closure, run it directly, if it is a specific class name. The dependency required for the constructor of this class is obtained by reflection, and the instantiation is completed.

* * focus on understanding the use of reflection in the following functions, it should be easy to understand * *

Build ($concrete) getDependencies (array $dependencies) resolvedNonClass (ReflectionParameter $parameter) resolvedClass (ReflectionParameter $parameter)

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Network Security

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report