eline\PipelineServiceProvider::class,
21 Illuminate\Queue\QueueServiceProvider::class,
22 Illuminate\Redis\RedisServiceProvider::class,
23 Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
24 Illuminate\Session\SessionServiceProvider::class,
25 Illuminate\Translation\TranslationServiceProvider::class,
26 Illuminate\Validation\ValidationServiceProvider::class,
27 Illuminate\View\ViewServiceProvider::class,
28
29 /*
30 * Package Service Providers...
31 */
32
33 /*
34 * Application Service Providers...
35 */
36 App\Providers\AppServiceProvider::class,
37 App\Providers\AuthServiceProvider::class,
38 // App\Providers\BroadcastServiceProvider::class,
39 App\Providers\EventServiceProvider::class,
40 App\Providers\RouteServiceProvider::class,
41 //添加刚刚生成的provider
42 App\Providers\TestServiceProvider::class,
43 ],
5、在IndexController文件中添加执行代码
1 namespace App\Http\Controllers;
2
3 use App\Contracts\Test;
4
5 class IndexController extends Controller
6 {
7
8 public function __construct(Test $test)
9 {
10 $this->test = $test;
11 }
12
13 public function index(Test $test)
14 {
15 app()->make('App\Contracts\Test')->doing();
16
17 echo '<br>';
18 //只有通过构造方法进行自动加载依赖的方式才能触发契约的when绑定
19 $this->test->doing();
20
21 echo '<br>';
22 //因为laravel中的上下文绑定只能具体到类,所以这里的$test实例依然为普通绑定
23 $test->doing();
24
25 }
26 }
运行后,会发现只有通过构造函数实例化的对象,才能触发额外的分支绑定。通过这个小例子,我们可以很清楚的理解契约了,就是在不同情况下的一个对接口的动态调用,算是java中多态和策略模式的另一实现方式。使用了这种实现方式,可以使我们在开发过程中的代码更加灵活,在改变实现方式的时候,只需改变provider中的实现绑定,即可快速实现需求变更。
可能有人会发现我们的demo在执行时需要显示的使用make方法,一点也不优雅,这和laravel所宣扬的思想还是有差距。那是因为还有一个facade门面功能还没有用上,后面我们会来探寻一下facade到底是个什么东西。