Laravel 5 目标不可实例化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29409353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:16:54  来源:igfitidea点击:

Laravel 5 target is not instantiable

phplaraveldependency-injectionioc-containerlaravel-5

提问by Hak

Multiple questions already asked about this topic, but I still have this problem and I don't have a clue on what the problem is.

关于这个主题已经提出了多个问题,但我仍然有这个问题,我不知道问题是什么。

I want to achieve that I can instantiate an interface instead of an implementation.

我想实现我可以实例化一个接口而不是一个实现。

I'm using Laravel 5, this is the code/structure:

我正在使用 Laravel 5,这是代码/结构:

In app, I have created a Contracts folder. In this folder I have Messenger.php:

在应用程序中,我创建了一个 Contracts 文件夹。在这个文件夹中,我有 Messenger.php:

Messenger.php

信使.php

<?php namespace App\Contracts;

interface Messenger {

    public function goodmorning($name);

}

In app/Services I have DailyMessenger.php

在应用程序/服务中,我有 DailyMessenger.php

<?php namespace App\Services;

use App\Contracts\Messenger;

class DailyMessenger implements Messenger {

    public function goodmorning($name)
    {
        return 'Goodmorning '. $name;
    }

}

Now I want to instantiate the interface in my controller:

现在我想在我的控制器中实例化接口:

public function __construct(Messenger $messenger)
    {
        $this->messenger = $messenger;
    }

Now, if I follow the documentation on the Laravel website I should only have to register this in the service container, which I do in the existing AppServiceProvider.php

现在,如果我遵循 Laravel 网站上的文档,我只需要在服务容器中注册它,我在现有的AppServiceProvider.php 中这样做

public function register()
    {
        $this->app->bind(
            'Illuminate\Contracts\Auth\Registrar',
            'App\Services\Registrar'
        );

        $this->app->bind('App\Contacts\Messenger', 'App\Services\DailyMessenger');
    }

If I visit appropriate route that maps to the controller I get the error:

如果我访问映射到控制器的适当路由,我会收到错误消息:

BindingResolutionException in Container.php line 785:
Target [App\Contracts\Messenger] is not instantiable.

I think I have followed the Laravel docs precisely but what am I missing? Thanks in advance :-)

我想我已经准确地遵循了 Laravel 文档,但我错过了什么?提前致谢 :-)

回答by Dan Krieger

Looks like you've spelled the namespace wrong when binding, used App\Contacts instead of App\Contracts. Should be:

看起来您在绑定时拼错了命名空间,使用了 App\Contacts 而不是 App\Contracts。应该:

$this->app->bind('App\Contracts\Messenger', 'App\Services\DailyMessenger');