laravel服务容器

publicindex.php

 1 <?php
 2 define('LARAVEL_START', microtime(true));
 3 //注册自动加载文件
 4 require __DIR__.'/../vendor/autoload.php';
 5 /**
 6  * 服务容器的生成
 7  * 主要实现了服务容器的实例化和基本注册
 8  *包括服务容器本身的注册,基础服务提供者注册,核心类别名注册和基本路径注册
 9  *
10 */
11 $app = require_once __DIR__.'/../bootstrap/app.php';
12 $kernel = $app->make(IlluminateContractsHttpKernel::class);
13 //处理请求
14 $response = $kernel->handle(
15     //请求实例的创建
16     $request = IlluminateHttpRequest::capture()
17 );
18 //发送http响应头和内容
19 $response->send();
20 
21 //程序的终止
22 $kernel->terminate($request, $response);
//用来实现服务容器的实例化过程
$app = new IlluminateFoundationApplication(
    realpath(__DIR__.'/../')
);

//下面代码向服务容器中绑定核心类服务,并返回核心类服务
$app->singleton(
    IlluminateContractsHttpKernel::class,
    AppHttpKernel::class
);
$app->singleton(
    IlluminateContractsConsoleKernel::class,
    AppConsoleKernel::class
);
$app->singleton(
    IlluminateContractsDebugExceptionHandler::class,
    AppExceptionsHandler::class
);

return $app;

  

服务绑定

究竟是什么和什么进行绑定呢?实际上可以简单地理解为一个服务和 一个关键字进行绑定,可以简单看做是一种键值对形式, 即一个“ key ”对应一个服务对于绑定服务的不同,需要服务容器中不同的绑定函数来实现,主要包括回调函数服务绑定和实例对象服务绑定:回调函数服务绑定的就是一个回调函数,而实例对象服务绑定的是一个实例对象回调函数的绑定还分为两种,一种是普通绑定,另一种是单例绑定普通绑定每次生成该服务的实例对象时都会生成一个新的实例对象,也就是说在程序的生命周期中,可以同时生成很多个这种实例对象,而单例绑定在生成一个实例对象后,如果再次生成就会返回第一次生成的实例对象,也就是在程序的生命周期中只能生成一个这样的实例对象,如果想使用就会获取之前生成的,也就是单例模式

其中:

$app->singleton(
    IlluminateContractsHttpKernel::class,
    AppHttpKernel::class
);
$app->singleton(
    IlluminateContractsConsoleKernel::class,
    AppConsoleKernel::class
);
$app->singleton(
    IlluminateContractsDebugExceptionHandler::class,
    AppExceptionsHandler::class
);

  

//$app->bind(AppServiceTestGeneralService::class,function($app){
// return new AppServiceTestGeneralService();
//});

//通过$bindings和$instances记录服务的绑定
//对于回调函数的服务绑定在$bindings
//shared为true单例模式 为false普通模式
$bindings=[
'AppServiceTestGeneralService::class'=>['concrete'=>{Closure::class},'shared'=>true],
'bbb'=>['concrete'=>{Closure::class},'shared'=>false],
];
//实例对象的绑定在$instances中
$instances= [
'IlluminateContractsHttpKernel::class'=>AppHttpKernel::class,
'IlluminateContractsConsoleKernel::class'=>AppConsoleKernel::class,
'lluminateContractsDebugExceptionHandler::class'=>AppConsoleKernel::class,
];

//除了上述回调函数绑定和实例对象绑定,还有一种:绑定具体类名称,本质上也是绑定回调函数的方式 只是回调函数是服务容器根据提供的参数自动生成的

//$app->bind(AppServiceTestServiceContract::class,AppServiceTestGeneralService);
//ServiceContract为一个几口,那么在绑定服务时可以通过类名或者接口名作为服务名,而服务是类名 ,那么对于服务名称是用类名还是用接口名好呢?
//答案是接口


服务的解析:



服务提供者:


laravel框架式通过服务提供者来解决服务绑定问题的,每一个功能模块都有一个服务提供者,而服务提供者继承了框架提供的illuminateServiceProvider抽象类,

该抽象类中提供一个函数register(),所以具体类需要实现register()函数,该函数就是用于服务绑定

创建服务提供者:
注册服务提供者:



















原文地址:https://www.cnblogs.com/sunlong88/p/9366774.html