我们先来看看官方文档中对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\\Routing\\Registrar 这个contract来演示一下吧。
首先,打开 app/Providers/AppServiceProvider.php,注意register方法:
$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 构造函数:
$this->middleware(\'guest\', [\'except\' => \'getLogout\']);
}
本文地址:https://www.stayed.cn/item/17585
转载请注明出处。
本站部分内容来源于网络,如侵犯到您的权益,请 联系我