0

我发现了很多关于我的问题的问题并尝试了(我认为)所有的解决方案,但我无法让它发挥作用。我可能忽略了一些非常容易的事情。

我正在使用 Laravel 5。我尝试实现存储库模式。我有一个 Eloquent 模型 '\Notos\Kind'。

然后我有这个界面:

namespace Notos\Contracts;

interface Kind
{
    public function findByName($name);
}

我的存储库如下所示:

namespace Notos\Repository;


use Illuminate\Database\Eloquent\Model;
use Notos\Contracts\Kind as KindContract;

class Kind implements KindContract
{
    protected $kind;

    public function __construct(Model $kind)
    {
        $this->kind = $kind;
    }

    public function findByName($name)
    {
        return $this->kind->firstOrCreate(array('name' => $name));
    }
}

我的服务提供商:

namespace Notos\Providers;

use Illuminate\Support\ServiceProvider;
use Notos\Kind;
use Notos\Repository\Kind as KindRepository;


class RepoServiceProvider extends ServiceProvider
{

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('Notos\Contracts\Kind', function ($app) {
            return new KindRepository(new Kind);
        });
    }
}

还有我使用存储库的控制器:

namespace Notos\Http\Controllers;

use Notos\Repository\Kind as KindRepository;

class KindController extends Controller
{
    protected $kind;

    public function __construct(KindRepository $kind)
    {
        $this->kind = $kind;
    }

    public function find($name)
    {
        return $this->kind->findByName($name);
    }
}

此提供程序在 config/app.php 中注册

当我尝试执行 KindController@find 时,出现此错误:

BindingResolutionException in Container.php line 785:
Target [Illuminate\Database\Eloquent\Model] is not instantiable.

我找不到我做错了什么。如果我将 __construct(Model $kind) 更改为 __construct(Kind $kind),它会完美运行。

有任何想法吗?谢谢

4

1 回答 1

1

首先,我建议您将函数添加到您的类名称中,例如,而不是Kind用于存储库使用KindRepository,与合同相同。否则,您将拥有 3 种类(当然在不同的命名空间中),但很难分析代码。

这里的问题是,在您KindController尝试KindRepository直接注入但在构造函数中使用Model. 它不起作用,因为Model它只是抽象类。你应该怎么做才能让它发挥作用?

在代码中:

$this->app->bind('Notos\Contracts\Kind', function ($app) {
            return new KindRepository(new Kind);
        });

你告诉 Laravel,当你使用Notos\Contracts\Kind它时,应该在构造函数中KindRepository为你创建Kind- 看看你在这里告诉过的关于 Contract,而不是关于存储库本身。

所以为了让它工作,你应该在你的控制器中使用不是你的存储库,而是你的合约。

而不是线:

use Notos\Repository\Kind as KindRepository;

你应该写:

use Notos\Contracts\Kind as KindRepository;

它现在应该可以工作了。

于 2015-02-15T09:43:32.263 回答