到这里,provider通过register注册在了服务容器内,provider的初始化工作也由boot函数完成,这个provider所提供的对象便可以直接拿来使用了。
还记得学习laravel框架使用方式的时候,文档建议我们把所有在应用初始化时需要完成的事情,都写在AppServiceProvider的boot方法里吗?看到这里我们能明白作为系统核心prvider的app是最早被加载的,因此也充当了一个钩子函数的角色。
1 namespace App\Contracts;
2
3 interface Test
4 {
5 public function doing();
6 }
1 namespace App\Services;
2
3 use App\Contracts\Test;
4
5 class TestService implements Test
6 {
7 public function doing()
8 {
9 echo 'this is TestService';
10 }
11 }
12
13
14 namespace App\Services;
15
16 use App\Contracts\Test;
17
18 class SecondTestService implements Test
19 {
20 public function doing()
21 {
22 echo 'this is SecondTestService';
23 }
24 }
1 namespace App\Providers;
2
3 use Illuminate\Support\ServiceProvider;
4
5 class TestServiceProvider extends ServiceProvider
6 {
7 /**
8 * Bootstrap any application services.
9 *
10 * @return void
11 */
12 public function boot()
13 {
14 //
15 }
16
17 public function register()
18 {
19 $this->app->bind('App\Contracts\Test', 'App\services\TestService');
20 //重点在于when方法确定运行环境,也就是执行上下文,needs为make所需的abstract类名或别名,give所传入的参数则是实际调用的实现类了
21 $this->app->when('App\Http\Controllers\IndexController')
22 ->needs('App\Contracts\Test')
23 ->give('App\Services\SecondTestService');
24 }
25 }
1 'providers' => [
2
3 /*
4 * Laravel Framework Service Providers...
5 */
6 Illuminate\Auth\AuthServiceProvider::class,
7 Illuminate\Broadcasting\BroadcastServiceProvider::class,
8 Illuminate\Bus\BusServiceProvider::class,
9 Illuminate\Cache\CacheServiceProvider::class,
10 Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
11 Illuminate\Cookie\CookieServiceProvider::class,
12 Illuminate\Database\DatabaseServiceProvider::class,
13 Illuminate\Encryption\EncryptionServiceProvider::class,
14 Illuminate\Filesystem\FilesystemServiceProvider::class,
15 Illuminate\Foundation\Providers\FoundationServiceProvider::class,
16 Illuminate\Hashing\HashServiceProvider::class,
17 Illuminate\Mail\MailServiceProvider::class,
18 Illuminate\Notifications\NotificationServiceProvider::class,
19 Illuminate\Pagination\PaginationServiceProvider::class,
20 Illuminate\Pip