Table of Contents
Service binding
instance
bind
singleton
alias
Service parsing
Home Backend Development PHP Tutorial Interpretation of Laravel service container (IocContainer)

Interpretation of Laravel service container (IocContainer)

Jul 06, 2018 pm 03:06 PM
laravel Source code analysis

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);
Copy after login

The object will be registered in the $instnces attribute of the service container

[
     'HelpSpot\Api' => $api//$api是API类的对象,这里简写了
 ]
Copy after login

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');
Copy after login

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);
    };
}
Copy after login

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
    ]
]
Copy after login

singleton

public function singleton($abstract, $concrete = null)
{
    $this->bind($abstract, $concrete, true);
}
Copy after login

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);
}
Copy after login

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');
Copy after login

After binding the service, you can parse the service object through

$this->app->make('service_alias');
Copy after login

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;
}
Copy after login

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;
    }
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.

Laravel vs CodeIgniter: Which framework is better for large projects? Laravel vs CodeIgniter: Which framework is better for large projects? Jun 04, 2024 am 09:09 AM

When choosing a framework for large projects, Laravel and CodeIgniter each have their own advantages. Laravel is designed for enterprise-level applications, offering modular design, dependency injection, and a powerful feature set. CodeIgniter is a lightweight framework more suitable for small to medium-sized projects, emphasizing speed and ease of use. For large projects with complex requirements and a large number of users, Laravel's power and scalability are more suitable. For simple projects or situations with limited resources, CodeIgniter's lightweight and rapid development capabilities are more ideal.

Laravel vs CodeIgniter: Which framework is better for small projects? Laravel vs CodeIgniter: Which framework is better for small projects? Jun 04, 2024 pm 05:29 PM

For small projects, Laravel is suitable for larger projects that require strong functionality and security. CodeIgniter is suitable for very small projects that require lightweight and ease of use.

Questions and Answers on PHP Enterprise Application Microservice Architecture Design Questions and Answers on PHP Enterprise Application Microservice Architecture Design May 07, 2024 am 09:36 AM

Microservice architecture uses PHP frameworks (such as Symfony and Laravel) to implement microservices and follows RESTful principles and standard data formats to design APIs. Microservices communicate via message queues, HTTP requests, or gRPC, and use tools such as Prometheus and ELKStack for monitoring and troubleshooting.

Which is the better template engine, Laravel or CodeIgniter? Which is the better template engine, Laravel or CodeIgniter? Jun 03, 2024 am 11:30 AM

Comparing Laravel's Blade and CodeIgniter's Twig template engine, choose based on project needs and personal preferences: Blade is based on MVC syntax, which encourages good code organization and template inheritance. Twig is a third-party library that provides flexible syntax, powerful filters, extended support, and security sandboxing.

See all articles