【问题标题】:Error __construct() must be an instance of Interface, none given错误 __construct() 必须是接口的实例,没有给出
【发布时间】:2013-11-26 21:00:19
【问题描述】:

我正在为 Laravel 开发一个包,但遇到一个错误,我不知道如何解决:

传递给 Cartalini\Drayman\Drayman::__construct() 的参数 1 必须是 Cartalini\Drayman\Repositories\UserRepositoryInterface 的实例,没有给出,在 /Applications/MAMP/htdocs/l4/app/controllers/HomeController 中调用。 php 在第 10 行并定义

这是我的代码...

namespace Cartalini\Drayman;

use Cartalini\Drayman\Repositories\UserRepositoryInterface;

class Drayman
{
    protected $user;

    public function __construct(UserRepositoryInterface $user)
    {
        $this->user = $user;
    }

    public function deliverBeer()
    {
        return $this->user->all();
    }
}

用户存储库...

namespace Cartalini\Drayman\Repositories;

class UserRepository implements UserRepositoryInterface
{
    public function all()
    {
        return User::all();
    }
}

UserRepositoryInterface...

namespace Cartalini\Drayman\Repositories;

interface UserRepositoryInterface
{
    public function all();
}

服务提供商...

public function register()
{
    $this->app->bind('Cartalini\Drayman\Repositories\UserRepositoryInterface', 'Cartalini\Drayman\Repositories\UserRepository');
}

最后是我的控制器...

use Cartalini\Drayman\Drayman as Drayman;

class HomeController extends BaseController 
{
    public function showWelcome()
    {
        $drayman = new Drayman;
        return $drayman->deliverBeer();
    }
}

谁能帮我调试一下?

【问题讨论】:

  • 您是否尝试阅读错误信息?
  • 消息说明了一切。 Daryamn 需要 UserRepositoryInterface 类型的参数,但您没有提供。
  • 关注 thisthis Laravel 中的包开发文章,我想你错过了几件事。

标签: php laravel


【解决方案1】:

在您的showWelcome 函数中:

public function showWelcome()
{
    // need to pass a UserRepositoryInterface object here:
    $drayman = new Drayman;
    return $drayman->deliverBeer();
}

由于您没有传递代码需要UserRepositoryInterface 对象,因此您会收到该错误。

【讨论】:

  • 这不是Laravel 的工作方式,它是关于Laravel package 的,这在理论上是正确的,但在这种情况下不是正确的答案。
  • 你知道 Laravel 是如何工作的吗?检查我在之前评论中提供的链接。
  • 我知道什么并不重要,但事实是你不知道Laravel,你回答了什么,如何在这里传递依赖,你甚至没有给出任何例子,你能做对吗?
  • 你有什么建议来解决这个问题,任何代码示例?您甚至没有根据纯 PHP 提供正确的代码,您在哪里传递了答案中的依赖关系?
  • ^ 建议在答案// need to pass a UserRepositoryInterface object here:
【解决方案2】:

可能有点晚了,但我遇到了同样的问题,原因是我的具体类没有实现它对应的接口类。实施后,一切顺利。
虽然你正确地实现了它,所以这个错误可能有几个原因,其中一个就是我所描述的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 2019-09-13
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    相关资源
    最近更新 更多