Interpretation of Laravel service container (IocContainer)
This article mainly introduces the interpretation of Laravel service container (IocContainer), which has certain reference value. Now I share it with everyone. Friends in need can refer to it
The core of Laravel is IocContainer, document It is called "service container". The service container is a powerful tool for managing class dependencies and performing dependency injection. The functional modules in Laravel such as Route, Eloquent ORM, Request, Response, etc. are actually related to Provided by core-independent class modules, these classes are actually responsible for the laravel service container from registration to instantiation and finally used by us.
If you don’t have a clear idea of what a service container is, I recommend a blog post to learn about the ins and outs of the service container: laravel’s magical service container
There are two concepts in the service container: inversion of control ( IOC) and dependency injection (DI):
Dependency injection and inversion of control are different descriptions of the same thing, and they describe it from different perspectives. Dependency injection is described from the perspective of the application. The application relies on the container to create and inject the external resources it needs. Inversion of control is described from the perspective of the container. The container controls the application, and the container reversely injects the external resources required by the application into the application.
In Laravel, the framework binds its various services to the service container. We can also bind custom services to the container. When an application needs to use a certain service, the service container will resolve the service and automatically resolve the dependencies between services and then hand it over to the application for use.
This article will discuss how service binding and parsing are implemented in Laravel
Service binding
Commonly used methods for binding services to containers include instance , bind, singleton, alias. Let’s take a look at them separately.
instance
Bind an existing object to the service container. When the service is subsequently resolved by name, the container will always return the bound instance.
$api = new HelpSpot\API(new HttpClient); $this->app->instance('HelpSpot\Api', $api);
The object will be registered in the $instnces attribute of the service container
[ 'HelpSpot\Api' => $api//$api是API类的对象,这里简写了 ]
bind
Bind the service to the service container
There are three binding methods :
1.绑定自身 $this->app->bind('HelpSpot\API', null); 2.绑定闭包 $this->app->bind('HelpSpot\API', function () { return new HelpSpot\API(); });//闭包直接提供类实现方式 $this->app->bind('HelpSpot\API', function ($app) { return new HelpSpot\API($app->make('HttpClient')); });//闭包返回需要依赖注入的类 3. 绑定接口和实现 $this->app->bind('Illuminate\Tests\Container\IContainerContractStub', 'Illuminate\Tests\Container\ContainerImplementationStub');
In the first case, in fact, inside the bind method, a closure is generated for the service through getClosure()
before binding the service. Let’s take a look at the source code of the bind method.
public function bind($abstract, $concrete = null, $shared = false) { $abstract = $this->normalize($abstract); $concrete = $this->normalize($concrete); //如果$abstract为数组类似['Illuminate/ServiceName' => 'service_alias'] //抽取别名"service_alias"并且注册到$aliases[]中 //注意:数组绑定别名的方式在5.4中被移除,别名绑定请使用下面的alias方法 if (is_array($abstract)) { list($abstract, $alias) = $this->extractAlias($abstract); $this->alias($abstract, $alias); } $this->dropStaleInstances($abstract); if (is_null($concrete)) { $concrete = $abstract; } //如果只提供$abstract,则在这里为其生成concrete闭包 if (! $concrete instanceof Closure) { $concrete = $this->getClosure($abstract, $concrete); } $this->bindings[$abstract] = compact('concrete', 'shared'); if ($this->resolved($abstract)) { $this->rebound($abstract); } } protected function getClosure($abstract, $concrete) { // $c 就是$container,即服务容器,会在回调时传递给这个变量 return function ($c, $parameters = []) use ($abstract, $concrete) { $method = ($abstract == $concrete) ? 'build' : 'make'; return $c->$method($concrete, $parameters); }; }
bind registers the service into the $bindings attribute of the service container, similar to this:
$bindings = [ 'HelpSpot\API' => [//闭包绑定 'concrete' => function ($app, $paramters = []) { return $app->build('HelpSpot\API'); }, 'shared' => false//如果是singleton绑定,这个值为true ] 'Illuminate\Tests\Container\IContainerContractStub' => [//接口实现绑定 'concrete' => 'Illuminate\Tests\Container\ContainerImplementationStub', 'shared' => false ] ]
singleton
public function singleton($abstract, $concrete = null) { $this->bind($abstract, $concrete, true); }
singleton method is a variant of the bind method, and binding one only requires Resolve the class or interface once to the container, and then the service will return the same instance for subsequent calls to the container
alias
Register the service and service alias to the container:
public function alias($abstract, $alias) { $this->aliases[$alias] = $this->normalize($abstract); }
The alias method is useful in the bind method mentioned above. It will register the corresponding relationship between the service alias and the service class in the $aliases attribute of the service container.
For example:
$this->app->alias('\Illuminate\ServiceName', 'service_alias');
After binding the service, you can parse the service object through
$this->app->make('service_alias');
when using it, so that you don’t have to write those longer class names when making. , the experience of using the make method has been greatly improved.
Service parsing
make: Parse the service object from the service container. This method receives the class name or interface name you want to parse as a parameter
/** * Resolve the given type from the container. * * @param string $abstract * @param array $parameters * @return mixed */ public function make($abstract, array $parameters = []) { //getAlias方法会假定$abstract是绑定的别名,从$aliases找到映射的真实类型名 //如果没有映射则$abstract即为真实类型名,将$abstract原样返回 $abstract = $this->getAlias($this->normalize($abstract)); // 如果服务是通过instance()方式绑定的,就直接解析返回绑定的service if (isset($this->instances[$abstract])) { return $this->instances[$abstract]; } // 获取$abstract接口对应的$concrete(接口的实现) $concrete = $this->getConcrete($abstract); if ($this->isBuildable($concrete, $abstract)) { $object = $this->build($concrete, $parameters); } else { //如果时接口实现这种绑定方式,通过接口拿到实现后需要再make一次才能 //满足isBuildable的条件 ($abstract === $concrete) $object = $this->make($concrete, $parameters); } foreach ($this->getExtenders($abstract) as $extender) { $object = $extender($object, $this); } //如果服务是以singleton方式注册进来的则,把构建好的服务对象放到$instances里, //避免下次使用时重新构建 if ($this->isShared($abstract)) { $this->instances[$abstract] = $object; } $this->fireResolvingCallbacks($abstract, $object); $this->resolved[$abstract] = true; return $object; } protected function getConcrete($abstract) { if (! is_null($concrete = $this->getContextualConcrete($abstract))) { return $concrete; } // 如果是$abstract之前没有注册类实现到服务容器里,则服务容器会认为$abstract本身就是接口的类实现 if (! isset($this->bindings[$abstract])) { return $abstract; } return $this->bindings[$abstract]['concrete']; } protected function isBuildable($concrete, $abstract) { return $concrete === $abstract || $concrete instanceof Closure; }
By using make After sorting out the method, we found that the function of the build method is to build the parsed service object. Let’s take a look at the specific process of building the object. (Reflection of PHP classes is used during the construction process to implement dependency injection of services)
public function build($concrete, array $parameters = []) { // 如果是闭包直接执行闭包并返回(对应闭包绑定) if ($concrete instanceof Closure) { return $concrete($this, $parameters); } // 使用反射ReflectionClass来对实现类进行反向工程 $reflector = new ReflectionClass($concrete); // 如果不能实例化,这应该是接口或抽象类,再或者就是构造函数是private的 if (! $reflector->isInstantiable()) { if (! empty($this->buildStack)) { $previous = implode(', ', $this->buildStack); $message = "Target [$concrete] is not instantiable while building [$previous]."; } else { $message = "Target [$concrete] is not instantiable."; } throw new BindingResolutionException($message); } $this->buildStack[] = $concrete; // 获取构造函数 $constructor = $reflector->getConstructor(); // 如果构造函数是空,说明没有任何依赖,直接new返回 if (is_null($constructor)) { array_pop($this->buildStack); return new $concrete; } // 获取构造函数的依赖(形参),返回一组ReflectionParameter对象组成的数组表示每一个参数 $dependencies = $constructor->getParameters(); $parameters = $this->keyParametersByArgument( $dependencies, $parameters ); // 构建构造函数需要的依赖 $instances = $this->getDependencies( $dependencies, $parameters ); array_pop($this->buildStack); return $reflector->newInstanceArgs($instances); } //获取依赖 protected function getDependencies(array $parameters, array $primitives = []) { $dependencies = []; foreach ($parameters as $parameter) { $dependency = $parameter->getClass(); // 某一依赖值在$primitives中(即build方法的$parameters参数)已提供 // $parameter->name返回参数名 if (array_key_exists($parameter->name, $primitives)) { $dependencies[] = $primitives[$parameter->name]; } elseif (is_null($dependency)) { // 参数的ReflectionClass为null,说明是基本类型,如'int','string' $dependencies[] = $this->resolveNonClass($parameter); } else { // 参数是一个类的对象, 则用resolveClass去把对象解析出来 $dependencies[] = $this->resolveClass($parameter); } } return $dependencies; } //解析出依赖类的对象 protected function resolveClass(ReflectionParameter $parameter) { try { // $parameter->getClass()->name返回的是类名(参数在typehint里声明的类型) // 然后递归继续make(在make时发现依赖类还有其他依赖,那么会继续make依赖的依赖 // 直到所有依赖都被解决了build才结束) return $this->make($parameter->getClass()->name); } catch (BindingResolutionException $e) { if ($parameter->isOptional()) { return $parameter->getDefaultValue(); } throw $e; } }
The service container is the core of laravel. It can solve the interdependencies between objects for us through dependency injection, and And through control inversion, specific behaviors are defined externally (Route, Eloquent, these are external modules, and they define their own behavioral specifications. The service container is responsible for these classes from registration to instantiation for your use).
For a class to be extracted by a container, it must first be registered with the container. Since laravel calls this container a service container, if we need a service, we must first register and bind the service to the container. Then the thing that provides the service and binds the service to the container is the service provider (ServiceProvider). The service provider is mainly divided into two parts, register (registration) and boot (boot, initialization). Due to space issues, please see another Laravel core interpretation - Service Provider (ServiceProvider) for the content of the Laravel service provider.
The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!
Related recommendations:
Laravel Core Interpretation Request
The above is the detailed content of Interpretation of Laravel service container (IocContainer). For more information, please follow other related articles on the PHP Chinese website!

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Notepad++7.3.1
Easy-to-use and free code editor