Laravel5中contracts详解
我们先来看看官方文档中对contracts的定义:
Laravel'sContractsareasetofinterfacesthatdefinethecoreservicesprovidedbytheframework.
意思是说Laravel的Contracts是一个由框架提供的定义了核心服务接口的集合。
也就是说,每一个Contract都是一个接口,对应一个框架核心服务。
那它的意义何在?官网给出的解释也很简单:使用接口是为了松耦合和简单。
先不讲大道理,先来点干货,看看怎么使用contract
先浏览下contracts接口列表:
Illuminate\Contracts\Auth\Guard Illuminate\Contracts\Auth\PasswordBroker Illuminate\Contracts\Bus\Dispatcher Illuminate\Contracts\Cache\Repository Illuminate\Contracts\Cache\Factory Illuminate\Contracts\Config\Repository Illuminate\Contracts\Container\Container Illuminate\Contracts\Cookie\Factory Illuminate\Contracts\Cookie\QueueingFactory Illuminate\Contracts\Encryption\Encrypter Illuminate\Contracts\Routing\Registrar
……太多了,懒得继续贴了,官网手册里有。我们就拿Illuminate\Contracts\Routing\Registrar这个contract来演示一下吧。
首先,打开app/Providers/AppServiceProvider.php,注意register方法:
publicfunctionregister() { $this->app->bind( 'Illuminate\Contracts\Auth\Registrar', 'App\Services\Registrar' ); }
$this->app就是Application对象,也是容器对象,通过$this->app->bind方法我们绑定了一个实现Illuminate\Contracts\Auth\Registrar接口的类App\Services\Registrar。
注意,Illuminate\Contracts\Auth\Registrar就是一个contract。App\Services\Registrar这个类文件在app/Services/Registrar.php。
接着我们看App\Http\Controllers\Auth\AuthController这个控制器类,看到它有__construct构造函数:
publicfunction__construct(Guard$auth,Registrar$registrar) { $this->auth=$auth; $this->registrar=$registrar;
$this->middleware('guest',['except'=>'getLogout']); }