Laravel study notes (29) Laravel core concepts (service concept container, dependency injection, binding, service providers, appearance)

  1. What is the server container
    service container is an ordinary container, for instance loaded class, and then taken out when needed. In more technical terms, is a service container implements Inversion of Control (Inversion of Control, abbreviated as IoC), meaning that under normal circumstances, when a required class A class B, we need themselves to new class B, means that we class B must know more details, such as the constructors, with increasing complexity of the project, this dependence is devastating. Inversion of Control, which means that, will take the initiative to obtain Class A Class B of the process upside down into the passive, class A just need to declare what it needs, and then provide the container.

The advantage of this is that class A does not depend on the implementation class B, and so to some extent, solve the coupling problem.

In Laravel service container, in order to achieve the inversion of control, you can have the following two ways:

Dependency injection (Dependency Injection).
Binding.

  1. What is decoupled

In short: A class is no longer directly dependent on Classes B, but generates a buffer between class A and Classes B, using the buffer to transfer data

  1. What is Dependency Injection

In short: A Class B Class calling methods when not in category A instantiate an object class B, but only introduced object class B in the function (for example using a constructor function), and in category A save the call. And examples of the process of class B, class A on the outside.

Traditional methods

clas A {
	public function __construct() {
		$this->obj = new B();
	}
}

$a = new A()

Dependency injection method

clas A {
	public function __construct(B $b) {
		$this->obj = $b;
	}
}

$b = new B();
$a = new A($b);

PS: PHP in order to solve some of the problems of dependency injection, introduces the concept of interface class ( Interface )

  1. PHP and Laravel life cycle
1. 模块初始化(MINIT),即调用 php.ini 中指明的扩展的初始化函数进行初始化工作,如 mysql 扩展。
2. 请求初始化(RINIT),即初始化为执行本次脚本所需要的变量名称和变量值内容的符号表,如 $_SESSION 变量。
3. 执行该 PHP 脚本。(Lravel生命周期开始)
	
	3.1 注册加载 composer 自动生成的 class loader,包括所有你 composer require 的依赖(对应代码 1.
	3.2 生成容器 Container,Application 实例,并向容器注册核心组件。这里牵涉到了容器 Container 和合同 Contracts,以及依赖注入等问题
	3.3 处理请求,生成并发送响应(对应代码 3,毫不夸张的说,你 99% 的代码都运行在这个小小的 handle 方法里面)。(具体代码的实现位置)
	3.4 请求结束,进行回调(对应代码 4,还记得可终止中间件吗?没错,就是在这里回调的)。

4. 请求处理完成 (Request Shutdown),按顺序调用各个模块的 RSHUTDOWN 方法,对每个变量调用 unset 函数,如 unset $_SESSION 变量。
5. 关闭模块 (Module Shutdown)PHP 调用每个扩展的 MSHUTDOWN 方法,这是各个模块最后一次释放内存的机会。这意味着没有下一个请求了。

PS: Other Documents

使用  bind()/singleton()  方法把容器与接口具体的实现类进行绑定:
app()->bind(MyInterface::class, MyClass::class);  // 使用一次绑定一次,下一次需要重新绑定
app()->singleton(MyInterface::class, MyClass::class);  // 一个周期只绑定一次,下一次不需要绑定

$instance = app()->make(MyInterface::class);
// 相当于
$instance = app(MyInterface::class);
// 相当于
$instance = new MyClass(new AnotherClass());

Binding service vessel

interface Fruit
{
    public function color();
}

class Apple implements Fruit
{
    public $color;

    public function __construct($color){
        $this->color = $color;
    }

    public function color(){
        return $this->color;
    }
}

app()->bind('Fruit', 'Apple');
// 当类Apple需要$color参数的时候,将red传给他
app()->bind(Fruit::class, Apple::class);
app()->when(Apple::class)->needs('$color')->give('22');
echo app(Fruit::class)->color();
  1. Service Provider Server Provider

Class used to bind to the vessel
corresponding to the tablet (s) into kits (container) in small lattices (service provider), a pill each grid management

// 新建一个服务提供者
php artisan make:provider AbcServiceProvider

Resolve order:

// public/index.php
$app = require_once __DIR__.'/../bootstrap/app.php';// 注册核心服务

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

// bootstrap/app.php
$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);
// vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php,执行handle方法中的sendRequestThroughRouter
    public function handle($request) {
    	...
    	$response = $this->sendRequestThroughRouter($request);
    }
	// 在sendRequestThroughRouter方法中再执行bootstrap()
   \Illuminate\Foundation\Bootstrap\RegisterProviders::class,

// 因为执行的是根据config/app.php加载的providers,例如
     /*
      * Application Service Providers...
      */
     App\Providers\AppServiceProvider::class,
     App\Providers\AuthServiceProvider::class,
     // App\Providers\BroadcastServiceProvider::class,
     App\Providers\EventServiceProvider::class,
     App\Providers\RouteServiceProvider::class,

So to register AbcServiceProvider in config / app.php in

After binding class and the container AbcServiceProvider

class AbcServiceProvider extends ServiceProvider implements DeferrableProvider
{
    public function register()
    {
        $this->app->singleton(Connection::class, function ($app) {
            return new Connection(config('riak'));
        });
    }

	// 默认生成的方法是没有这个的
	// 使用延时服务提供者后,只有在真正调用这个服务器提供者的时候,才会进行加载,节约内存
	// 实现方法:implements DeferrableProvider和public function provides()和类名Connection::class
	// 可以参考缓存的服务提供者vendor/laravel/framework/src/Illuminate/Cache/CacheServiceProvider.php
    public function provides()
    {
        return [Connection::class];
    }
}
  1. Facade of the appearance of the system in simple terms Laravel

Loading a skin services are AliasLoader components to complete:

First of all, reads all the "look" aliases service configuration from the configuration file config / app.php in;

And then read from the manifest file alias service $ app-> make (PackageManifest :: class) -> aliases ();

(Dynamic when first introduced in the use of "appearance" service class and then register it.) After the merger of the two will be injected into the configuration array to complete the registration AliasLoader

After calling the last appearance in the client service, it will call the method to achieve getFacadeAccessor "appearance" of obtaining the name of the component (service or interface); then parse out Laravel related services from the service container.

Published 40 original articles · won praise 0 · Views 761

Guess you like

Origin blog.csdn.net/qj4865/article/details/104378314