laravel 生命周期与框架精髓

生命周期

  1. 所有请求必定首先通过 public/index.php
  2. 在上述这个文件中首先加载 composer 自动加载文件,然后从 bootstrap/app.php 实例化一个服务容器。
  3. 接下来,框架会根据请求类型传送请求至 app/Http/Kernel.php 或者app/Console/Kernel.php
  4. app/Http/Kernel.php扩展了Illuminate\Foundation\Http\Kernel类,父类强制在处理请求前应该做哪些操作,操作内容都放到了bootstrappers数组里面。子类在数组middleware中规定了请求在被处理前必须经过的一些处理。
  5. 实例化对应 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"...
});
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值