在Laravel5中出现了一个新的东西,叫做contracts,那么它到底是什么?有什么用?怎么用?我们就来探讨下吧。
我们先来看看官方文档中对contracts的定义:
Laravel's Contracts are a set of interfaces that define the core services provided by the framework.
意思是说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方法:
public function register()
{
$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 构造函数:
public function __construct(Guard $auth, Registrar $registrar)
{
$this->auth = $auth;
$this->registrar = $registrar;
$this->middleware('guest', ['except' => 'getLogout']);
}
以上就是Laravel5中contracts详解的详细内容,更多请关注0133技术站其它相关文章!