laravel5.5契约

无规矩不成方圆,

Laravel 的契约是一组定义框架提供的核心服务的接口,规定了实现该接口的规范。

为什么要使用接口

首先,让我们来看一些高耦合缓存实现的代码。如下:

<?php

namespace AppOrders;

class Repository
{

    protected $cache;

    //缓存依赖一个特定的类Memcached
    public function __construct(SomePackageCacheMemcached $cache)
    {
        $this->cache = $cache;
    }

    public function find($id)
    {
        if ($this->cache->has($id))    {
            //
        }
    }
}

比起上面的做法,我们可以使用一个简单的、与扩展包无关的接口来改进我们的代码:

<?php

namespace AppOrders;

use IlluminateContractsCacheRepository as Cache;

class Repository
{

    protected $cache;

    //缓存依赖于接口Cache
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }
}

当所有 Laravel 的服务都使用简洁的接口定义,就很容易判断给定服务提供的功能。 可以将契约视为说明框架功能的简洁文档。

使用契约

要获得一个契约的实现,你只需要被解析的类的构造函数中添加「类型提示」即可。

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

<?php

namespace AppListeners;

use AppUser;
use AppEventsOrderWasPlaced;
use IlluminateContractsRedisDatabase;

class CacheOrderInformation
{
    /**
     * Redis 数据库实现。
     */
    protected $redis;

    /**
     * 创建事件处理器实例。
     *
     * @param  Database  $redis
     * @return void
     */
    public function __construct(Database $redis)
    {
        $this->redis = $redis;
    }

    /**
     * 处理事件。
     *
     * @param  OrderWasPlaced  $event
     * @return void
     */
    public function handle(OrderWasPlaced $event)
    {
        //
    }
}
原文地址:https://www.cnblogs.com/redirect/p/8658706.html