4

上的文档laravel.com是不够的。任何人都可以指导我如何Laravel从头开始创建合同。

我需要在Laravel. 现在,我正在使用Laravel 5.4

4

2 回答 2

4

合同只是php interfaces. 我们一直在使用它们,这并不是什么新鲜事。

Contracts/Interfaces帮助我们维护一个松散耦合的代码库。请参阅下面文档中的示例。

<?php

namespace App\Orders;

class Repository
{
    /**
     * The cache instance.
     */
    protected $cache;

    /**
     * Create a new repository instance.
     *
     * @param  \SomePackage\Cache\Memcached  $cache
     * @return void
     */
    public function __construct(\SomePackage\Cache\Memcached $cache)
    {
        $this->cache = $cache;
    }

    /**
     * Retrieve an Order by ID.
     *
     * @param  int  $id
     * @return Order
     */
    public function find($id)
    {
        if ($this->cache->has($id))    {
            //
        }
    }
}

在这里,当实例化时,Repository我们应该提供一个\SomePackage\Cache\Memcached实例以使代码正常工作。因此,我们的代码与\SomePackage\Cache\Memcached. 现在看看下面的代码。

<?php

namespace App\Orders;

use Illuminate\Contracts\Cache\Repository as Cache;

class Repository
{
    /**
     * The cache instance.
     */
    protected $cache;

    /**
     * Create a new repository instance.
     *
     * @param  Cache  $cache
     * @return void
     */
    public function __construct(Cache $cache)
    {
        $this->cache = $cache;
    }
}

同样的事情,但现在我们只需要提供一些缓存接口。在幕后你可以做这样的事情。

<?php

namespace App\Orders;

use Illuminate\Contracts\Cache\Repository as Cache;

class RedisCache implements Cache {
     // 
}

上面Repository实例化的时候,php会查看Illuminate\Contracts\Cache\Repository和它已经被RedisCache类实现了。

于 2017-02-02T05:44:49.803 回答
4

恐怕Gayan 的回答需要进一步阐述才能解决Rajan 的问题

是的 Gayan 是正确的,创建一个Contract类基本上意味着创建一个 php interface

继续上面的 Cache 示例,如果我们查看它的源代码(您可以在这个 Github repo 文件中找到它),我们可以看到类似这样的内容

<?php

namespace Illuminate\Contracts\Cache;

use Closure;

interface Repository
{
    /**
     * Determine if an item exists in the cache.
     *
     * @param  string  $key
     * @return bool
     */
    public function has($key);

    /**
     * Retrieve an item from the cache by key.
     *
     * @param  string  $key
     * @param  mixed   $default
     * @return mixed
     */
    public function get($key, $default = null);

    // the rest...
}

如果我们在我们的 laravel 应用程序中使用这个接口,我们就说它是一个“合约”。它声明了一个类如果实现了这个接口应该有什么方法/属性。例如在我们的应用程序中......

<?php

namespace App\Whatever;

use Illuminate\Contracts\Cache\Repository;

class Foo implements Repository {
     // 
}

然后类Foo将需要有方法hasget以实现Repository合同中规定的内容。

于 2019-11-07T17:00:29.193 回答