生命周期
- 所有请求必定首先通过
public/index.php
。 - 在上述这个文件中首先加载 composer 自动加载文件,然后从
bootstrap/app.php
实例化一个服务容器。 - 接下来,框架会根据请求类型传送请求至
app/Http/Kernel.php
或者app/Console/Kernel.php
。 app/Http/Kernel.php
扩展了Illuminate\Foundation\Http\Kernel
类,父类强制在处理请求前应该做哪些操作,操作内容都放到了bootstrappers
数组里面。子类在数组middleware
中规定了请求在被处理前必须经过的一些处理。- 实例化对应 Kernel,处理请求,返回响应内容。请求将作为参数传入 handle 方法,返回值就是响应内容。
引导 Kernel 最重要的部分是加载服务提供者。
config/app.php
配置了应用用到的服务提供者。所有服务提供者都会调用各自 register 方法。一旦所有的 register 方法都被调用后,各自 boot 方法就会被调用。一旦应用被引导成功,请求会被 router 处理。
服务容器
服务容器是一个用来管理类依赖和执行依赖注入的工具。
绑定
$this->app->bind('HelpSpot\API', function ($app) {
return new HelpSpot\API($app->make('HttpClient'));
});
// Note that we receive the container itself as an argument to the resolver. We can then use the container to resolve sub-dependencies of the object we are building.
$this->app->singleton('HelpSpot\API', function ($app) {
return new HelpSpot\API($app->make('HttpClient'));
}); // 同上,单例模式
$api = new HelpSpot\API(new HttpClient);
$this->app->instance('HelpSpot\API', $api); // 绑定实例
$this->app->when('App\Http\Controllers\UserController')
->needs('$variableName')
->give($value);
$this->app->bind(
'App\Contracts\EventPusher',
'App\Services\RedisEventPusher'
); // 绑定接口到实例
$this->app->when(PhotoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk('local');
});
$this->app->when(VideoController::class)
->needs(Filesystem::class)
->give(function () {
return Storage::disk('s3');
});
// 上下文绑定
$this->app->bind('SpeedReport', function () {
//
});
$this->app->bind('MemoryReport', function () {
//
});
$this->app->tag(['SpeedReport', 'MemoryReport'], 'reports');
$this->app->bind('ReportAggregator', function ($app) {
return new ReportAggregator($app->tagged('reports'));
});
// 给绑定设置标签
$this->app->extend(Service::class, function($service) {
return new DecoratedService($service);
});
// 当服务已经被解析,可以用来修改服务
解析
$api = $this->app->make('HelpSpot\API');
$api = resolve('HelpSpot\API');
$api = $this->app->makeWith('HelpSpot\API', ['id' => 1]);
public function __construct(UserRepository $users)
容器事件
$this->app->resolving(function ($object, $app) {
// Called when container resolves object of any type...
});
$this->app->resolving(HelpSpot\API::class, function ($api, $app) {
// Called when container resolves objects of type "HelpSpot\API"...
});