Service providers are the central place of all Laravel application bootstrapping. Your own application, as well as all of Laravel's core services are bootstrapped via service providers.
Service Providers (服务提供者) 是 Laravel 「引导」过程的核心。这个「引导」过程可以理解成「电脑从按下开机按钮到完全进入桌面」这段时间系统干的事。
// Illuminate\Foundation\Http
class Kernel implements KernelContract
{
public function handle($request)
try {
//...
$response = $this->sendRequestThroughRouter($request);
} catch (Exception $e) {
//...
}
}
}
// Illuminate\Foundation\Http
class Kernel implements KernelContract
{
protected function sendRequestThroughRouter($request)
{
//...
// 按顺序执行每个 bootstrapper
$this->bootstrap();
//...
}
}
// Illuminate\Foundation\Http
class Kernel implements KernelContract
{
public function bootstrap()
{
if (! $this->app->hasBeenBootstrapped()) {
$this->app->bootstrapWith($this->bootstrappers());
}
}
}
{
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
public function boot()
{
// 这里使用 make() 方法,可以更直观
$this->app->make('view')->composer('view', function () {
//
});
// 或者使用 view() 辅助函数
view()->composer('view', function () {
//
});
}
}
php artisan make:provider MyServiceProvider
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class MyServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->bind(MyInterface::class, MyClass::class);
}
}
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Routing\ResponseFactory;
class MyServiceProvider extends ServiceProvider
{
/**
* boot() 方法中可以使用依赖注入。
* 这是因为在 Illuminate\Foundation\Application 类中,
* 通过 bootProvider() 方法中的 $this->call([$provider, 'boot'])
* 来执行 Service Provider 的 boot() 方法
* Container 的 call() 方法作用,可以参考上一篇文章
*/
public function boot(ResponseFactory $response)
{
$response->macro('caps', function ($value) {
//
});
}
}
'providers' => [
/*
* Laravel Framework Service Providers...
*/
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\MyServiceProvider::class,
],
namespace Illuminate\Hashing;
use Illuminate\Support\ServiceProvider;
class HashServiceProvider extends ServiceProvider
{
/**
* 如果延时加载,$defer 必须设置为 true 。
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('hash', function () {
return new BcryptHasher;
});
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['hash'];
}
}
class MyController extends Controller
{
public function test()
{
// 此时才会注册 `HashServiceProvider`
$hash = $this->app->make('hash');
$hash->make('teststring');
// 或
\Hash::make('teststring');
}
}