Skip to content

合约

介绍

Laravel 的合约是一组接口,定义了框架提供的核心服务。例如,Illuminate\Contracts\Queue\Queue 合约定义了队列作业所需的方法,而 Illuminate\Contracts\Mail\Mailer 合约定义了发送电子邮件所需的方法。

每个合约都有框架提供的相应实现。例如,Laravel 提供了具有多种驱动的队列实现,以及由 SwiftMailer 驱动的邮件实现。

所有的 Laravel 合约都在 它们自己的 GitHub 仓库 中。这为所有可用合约提供了一个快速参考点,同时也是一个可以被包开发者利用的单一、解耦的包。

合约与门面

Laravel 的门面和辅助函数提供了一种简单的方法来利用 Laravel 的服务,而无需在服务容器中进行类型提示和解析合约。在大多数情况下,每个门面都有一个等效的合约。

与门面不同,门面不需要在类的构造函数中要求它们,而合约允许你为类定义显式依赖性。一些开发者更喜欢以这种方式显式定义他们的依赖性,因此更喜欢使用合约,而其他开发者则享受门面的便利。

大多数应用程序无论你是偏好门面还是合约都可以正常运行。然而,如果你正在构建一个包,你应该强烈考虑使用合约,因为它们在包上下文中更容易测试。

何时使用合约

如其他地方所述,使用合约或门面的决定很大程度上取决于个人品味和开发团队的品味。合约和门面都可以用来创建健壮、经过良好测试的 Laravel 应用程序。只要你保持类的职责集中,你会发现使用合约和门面之间几乎没有实际差异。

然而,你可能仍然对合约有几个问题。例如,为什么要使用接口?使用接口不是更复杂吗?让我们将使用接口的原因简化为以下几个标题:松耦合和简洁性。

松耦合

首先,让我们回顾一些与缓存实现紧密耦合的代码。考虑以下代码:

<?php

namespace App\Orders;

class Repository
{
    /**
     * 缓存实例。
     */
    protected $cache;

    /**
     * 创建一个新的仓库实例。
     *
     * @param  \SomePackage\Cache\Memcached  $cache
     * @return void
     */
    public function __construct(\SomePackage\Cache\Memcached $cache)
    {
        $this->cache = $cache;
    }

    /**
     * 根据 ID 检索订单。
     *
     * @param  int  $id
     * @return Order
     */
    public function find($id)
    {
        if ($this->cache->has($id)) {
            //
        }
    }
}

在这个类中,代码与给定的缓存实现紧密耦合。它紧密耦合是因为我们依赖于来自包供应商的具体缓存类。如果该包的 API 发生变化,我们的代码也必须更改。

同样,如果我们想用另一种技术(如 Redis)替换我们的底层缓存技术(如 Memcached),我们又必须修改我们的仓库。我们的仓库不应该对谁提供数据或如何提供数据有太多了解。

相反,我们可以通过依赖于一个简单的、与供应商无关的接口来改进我们的代码:

<?php

namespace App\Orders;

use Illuminate\Contracts\Cache\Repository as Cache;

class Repository
{
    /**
     * 缓存实例。
     */
    protected $cache;

    /**
     * 创建一个新的仓库实例。
     *
     * @param  Cache  $cache
     * @return void
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }
}

现在,代码不再与任何特定供应商甚至 Laravel 耦合。由于合约包不包含实现和依赖项,你可以轻松地为任何给定合约编写替代实现,允许你在不修改任何使用缓存的代码的情况下替换缓存实现。

简洁性

当 Laravel 的所有服务都在简单的接口中定义时,很容易确定给定服务提供的功能。合约作为框架功能的简洁文档。

此外,当你依赖于简单的接口时,你的代码更容易理解和维护。与其追踪一个大型复杂类中可用的方法,不如参考一个简单、干净的接口。

如何使用合约

那么,如何获得合约的实现呢?其实很简单。

Laravel 中的许多类型的类都是通过服务容器解析的,包括控制器、事件监听器、中间件、队列作业,甚至是路由闭包。因此,要获得合约的实现,你只需在被解析类的构造函数中“类型提示”接口。

例如,看看这个事件监听器:

<?php

namespace App\Listeners;

use App\Events\OrderWasPlaced;
use App\User;
use Illuminate\Contracts\Redis\Factory;

class CacheOrderInformation
{
    /**
     * Redis 工厂实现。
     */
    protected $redis;

    /**
     * 创建一个新的事件处理程序实例。
     *
     * @param  Factory  $redis
     * @return void
     */
    public function __construct(Factory $redis)
    {
        $this->redis = $redis;
    }

    /**
     * 处理事件。
     *
     * @param  OrderWasPlaced  $event
     * @return void
     */
    public function handle(OrderWasPlaced $event)
    {
        //
    }
}

当事件监听器被解析时,服务容器将读取类构造函数上的类型提示,并注入适当的值。要了解有关在服务容器中注册内容的更多信息,请查看其文档

合约参考

此表提供了所有 Laravel 合约及其等效门面的快速参考:

合约参考门面
[Illuminate\Contracts\Auth\Access\Authorizable](https://github.com/illuminate/contracts/blob/7.x/Auth/Access/Authorizable.php) 
[Illuminate\Contracts\Auth\Access\Gate](https://github.com/illuminate/contracts/blob/7.x/Auth/Access/Gate.php)`Gate`
[Illuminate\Contracts\Auth\Authenticatable](https://github.com/illuminate/contracts/blob/7.x/Auth/Authenticatable.php) 
[Illuminate\Contracts\Auth\CanResetPassword](https://github.com/illuminate/contracts/blob/7.x/Auth/CanResetPassword.php) 
[Illuminate\Contracts\Auth\Factory](https://github.com/illuminate/contracts/blob/7.x/Auth/Factory.php)`Auth`
[Illuminate\Contracts\Auth\Guard](https://github.com/illuminate/contracts/blob/7.x/Auth/Guard.php)`Auth::guard()`
[Illuminate\Contracts\Auth\PasswordBroker](https://github.com/illuminate/contracts/blob/7.x/Auth/PasswordBroker.php)`Password::broker()`
[Illuminate\Contracts\Auth\PasswordBrokerFactory](https://github.com/illuminate/contracts/blob/7.x/Auth/PasswordBrokerFactory.php)`Password`
[Illuminate\Contracts\Auth\StatefulGuard](https://github.com/illuminate/contracts/blob/7.x/Auth/StatefulGuard.php) 
[Illuminate\Contracts\Auth\SupportsBasicAuth](https://github.com/illuminate/contracts/blob/7.x/Auth/SupportsBasicAuth.php) 
[Illuminate\Contracts\Auth\UserProvider](https://github.com/illuminate/contracts/blob/7.x/Auth/UserProvider.php) 
[Illuminate\Contracts\Bus\Dispatcher](https://github.com/illuminate/contracts/blob/7.x/Bus/Dispatcher.php)`Bus`
[Illuminate\Contracts\Bus\QueueingDispatcher](https://github.com/illuminate/contracts/blob/7.x/Bus/QueueingDispatcher.php)`Bus::dispatchToQueue()`
[Illuminate\Contracts\Broadcasting\Factory](https://github.com/illuminate/contracts/blob/7.x/Broadcasting/Factory.php)`Broadcast`
[Illuminate\Contracts\Broadcasting\Broadcaster](https://github.com/illuminate/contracts/blob/7.x/Broadcasting/Broadcaster.php)`Broadcast::connection()`
[Illuminate\Contracts\Broadcasting\ShouldBroadcast](https://github.com/illuminate/contracts/blob/7.x/Broadcasting/ShouldBroadcast.php) 
[Illuminate\Contracts\Broadcasting\ShouldBroadcastNow](https://github.com/illuminate/contracts/blob/7.x/Broadcasting/ShouldBroadcastNow.php) 
[Illuminate\Contracts\Cache\Factory](https://github.com/illuminate/contracts/blob/7.x/Cache/Factory.php)`Cache`
[Illuminate\Contracts\Cache\Lock](https://github.com/illuminate/contracts/blob/7.x/Cache/Lock.php) 
[Illuminate\Contracts\Cache\LockProvider](https://github.com/illuminate/contracts/blob/7.x/Cache/LockProvider.php) 
[Illuminate\Contracts\Cache\Repository](https://github.com/illuminate/contracts/blob/7.x/Cache/Repository.php)`Cache::driver()`
[Illuminate\Contracts\Cache\Store](https://github.com/illuminate/contracts/blob/7.x/Cache/Store.php) 
[Illuminate\Contracts\Config\Repository](https://github.com/illuminate/contracts/blob/7.x/Config/Repository.php)`Config`
[Illuminate\Contracts\Console\Application](https://github.com/illuminate/contracts/blob/7.x/Console/Application.php) 
[Illuminate\Contracts\Console\Kernel](https://github.com/illuminate/contracts/blob/7.x/Console/Kernel.php)`Artisan`
[Illuminate\Contracts\Container\Container](https://github.com/illuminate/contracts/blob/7.x/Container/Container.php)`App`
[Illuminate\Contracts\Cookie\Factory](https://github.com/illuminate/contracts/blob/7.x/Cookie/Factory.php)`Cookie`
[Illuminate\Contracts\Cookie\QueueingFactory](https://github.com/illuminate/contracts/blob/7.x/Cookie/QueueingFactory.php)`Cookie::queue()`
[Illuminate\Contracts\Database\ModelIdentifier](https://github.com/illuminate/contracts/blob/7.x/Database/ModelIdentifier.php) 
[Illuminate\Contracts\Debug\ExceptionHandler](https://github.com/illuminate/contracts/blob/7.x/Debug/ExceptionHandler.php) 
[Illuminate\Contracts\Encryption\Encrypter](https://github.com/illuminate/contracts/blob/7.x/Encryption/Encrypter.php)`Crypt`
[Illuminate\Contracts\Events\Dispatcher](https://github.com/illuminate/contracts/blob/7.x/Events/Dispatcher.php)`Event`
[Illuminate\Contracts\Filesystem\Cloud](https://github.com/illuminate/contracts/blob/7.x/Filesystem/Cloud.php)`Storage::cloud()`
[Illuminate\Contracts\Filesystem\Factory](https://github.com/illuminate/contracts/blob/7.x/Filesystem/Factory.php)`Storage`
[Illuminate\Contracts\Filesystem\Filesystem](https://github.com/illuminate/contracts/blob/7.x/Filesystem/Filesystem.php)`Storage::disk()`
[Illuminate\Contracts\Foundation\Application](https://github.com/illuminate/contracts/blob/7.x/Foundation/Application.php)`App`
[Illuminate\Contracts\Hashing\Hasher](https://github.com/illuminate/contracts/blob/7.x/Hashing/Hasher.php)`Hash`
[Illuminate\Contracts\Http\Kernel](https://github.com/illuminate/contracts/blob/7.x/Http/Kernel.php) 
[Illuminate\Contracts\Mail\MailQueue](https://github.com/illuminate/contracts/blob/7.x/Mail/MailQueue.php)`Mail::queue()`
[Illuminate\Contracts\Mail\Mailable](https://github.com/illuminate/contracts/blob/7.x/Mail/Mailable.php) 
[Illuminate\Contracts\Mail\Mailer](https://github.com/illuminate/contracts/blob/7.x/Mail/Mailer.php)`Mail`
[Illuminate\Contracts\Notifications\Dispatcher](https://github.com/illuminate/contracts/blob/7.x/Notifications/Dispatcher.php)`Notification`
[Illuminate\Contracts\Notifications\Factory](https://github.com/illuminate/contracts/blob/7.x/Notifications/Factory.php)`Notification`
[Illuminate\Contracts\Pagination\LengthAwarePaginator](https://github.com/illuminate/contracts/blob/7.x/Pagination/LengthAwarePaginator.php) 
[Illuminate\Contracts\Pagination\Paginator](https://github.com/illuminate/contracts/blob/7.x/Pagination/Paginator.php) 
[Illuminate\Contracts\Pipeline\Hub](https://github.com/illuminate/contracts/blob/7.x/Pipeline/Hub.php) 
[Illuminate\Contracts\Pipeline\Pipeline](https://github.com/illuminate/contracts/blob/7.x/Pipeline/Pipeline.php) 
[Illuminate\Contracts\Queue\EntityResolver](https://github.com/illuminate/contracts/blob/7.x/Queue/EntityResolver.php) 
[Illuminate\Contracts\Queue\Factory](https://github.com/illuminate/contracts/blob/7.x/Queue/Factory.php)`Queue`
[Illuminate\Contracts\Queue\Job](https://github.com/illuminate/contracts/blob/7.x/Queue/Job.php) 
[Illuminate\Contracts\Queue\Monitor](https://github.com/illuminate/contracts/blob/7.x/Queue/Monitor.php)`Queue`
[Illuminate\Contracts\Queue\Queue](https://github.com/illuminate/contracts/blob/7.x/Queue/Queue.php)`Queue::connection()`
[Illuminate\Contracts\Queue\QueueableCollection](https://github.com/illuminate/contracts/blob/7.x/Queue/QueueableCollection.php) 
[Illuminate\Contracts\Queue\QueueableEntity](https://github.com/illuminate/contracts/blob/7.x/Queue/QueueableEntity.php) 
[Illuminate\Contracts\Queue\ShouldQueue](https://github.com/illuminate/contracts/blob/7.x/Queue/ShouldQueue.php) 
[Illuminate\Contracts\Redis\Factory](https://github.com/illuminate/contracts/blob/7.x/Redis/Factory.php)`Redis`
[Illuminate\Contracts\Routing\BindingRegistrar](https://github.com/illuminate/contracts/blob/7.x/Routing/BindingRegistrar.php)`Route`
[Illuminate\Contracts\Routing\Registrar](https://github.com/illuminate/contracts/blob/7.x/Routing/Registrar.php)`Route`
[Illuminate\Contracts\Routing\ResponseFactory](https://github.com/illuminate/contracts/blob/7.x/Routing/ResponseFactory.php)`Response`
[Illuminate\Contracts\Routing\UrlGenerator](https://github.com/illuminate/contracts/blob/7.x/Routing/UrlGenerator.php)`URL`
[Illuminate\Contracts\Routing\UrlRoutable](https://github.com/illuminate/contracts/blob/7.x/Routing/UrlRoutable.php) 
[Illuminate\Contracts\Session\Session](https://github.com/illuminate/contracts/blob/7.x/Session/Session.php)`Session::driver()`
[Illuminate\Contracts\Support\Arrayable](https://github.com/illuminate/contracts/blob/7.x/Support/Arrayable.php) 
[Illuminate\Contracts\Support\Htmlable](https://github.com/illuminate/contracts/blob/7.x/Support/Htmlable.php) 
[Illuminate\Contracts\Support\Jsonable](https://github.com/illuminate/contracts/blob/7.x/Support/Jsonable.php) 
[Illuminate\Contracts\Support\MessageBag](https://github.com/illuminate/contracts/blob/7.x/Support/MessageBag.php) 
[Illuminate\Contracts\Support\MessageProvider](https://github.com/illuminate/contracts/blob/7.x/Support/MessageProvider.php) 
[Illuminate\Contracts\Support\Renderable](https://github.com/illuminate/contracts/blob/7.x/Support/Renderable.php) 
[Illuminate\Contracts\Support\Responsable](https://github.com/illuminate/contracts/blob/7.x/Support/Responsable.php) 
[Illuminate\Contracts\Translation\Loader](https://github.com/illuminate/contracts/blob/7.x/Translation/Loader.php) 
[Illuminate\Contracts\Translation\Translator](https://github.com/illuminate/contracts/blob/7.x/Translation/Translator.php)`Lang`
[Illuminate\Contracts\Validation\Factory](https://github.com/illuminate/contracts/blob/7.x/Validation/Factory.php)`Validator`
[Illuminate\Contracts\Validation\ImplicitRule](https://github.com/illuminate/contracts/blob/7.x/Validation/ImplicitRule.php) 
[Illuminate\Contracts\Validation\Rule](https://github.com/illuminate/contracts/blob/7.x/Validation/Rule.php) 
[Illuminate\Contracts\Validation\ValidatesWhenResolved](https://github.com/illuminate/contracts/blob/7.x/Validation/ValidatesWhenResolved.php) 
[Illuminate\Contracts\Validation\Validator](https://github.com/illuminate/contracts/blob/7.x/Validation/Validator.php)`Validator::make()`
[Illuminate\Contracts\View\Engine](https://github.com/illuminate/contracts/blob/7.x/View/Engine.php) 
[Illuminate\Contracts\View\Factory](https://github.com/illuminate/contracts/blob/7.x/View/Factory.php)`View`
[Illuminate\Contracts\View\View](https://github.com/illuminate/contracts/blob/7.x/View/View.php)`View::make()`