在服务提供商中绑定时给出

在服务提供商中绑定时给出

本文介绍了错误响应内容必须是实现__toString()的字符串或对象.在服务提供商中绑定时给出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过绑定到Laravel5服务容器的接口来解析具体的类.

I'm trying to resolve a concrete class via an interface bound to the Laravel5 service container.

namespace App\Services;

use App\Services\FileMakerInterface;

class SSCSimpleFM implements FileMakerInterface {

    protected $username;
    protected $password;
    protected $host;
    protected $database;

    public function __construct($config){
        $this->username = $config['username'];
        $this->password = $config['password'];
        $this->host     = $config['host'];
        $this->database = $config['database'];
    }
}

我的界面

namespace App\Services;

interface FileMakerInterface {

}

我的服务提供商

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Services\SSCSimpleFM;

class FileMakerServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->app->bind('App\Services\FileMakerInterface', function ($app){
            $username = env('FM_USERNAME');
            $password = env('FM_PASSWORD');
            $host     = env('FM_HOST');
            $database = env('FM_DATABASE');
            return new SSCSimpleFM(compact('username', 'password', 'host', 'database'));
        });
    }
}

绑定本身有效.如果在具体类的构造函数中为dd,我可以在浏览器中看到它,但是当我尝试在测试控制器中使用该接口时:

The binding itself works. If a dd in the concrete class' constructor I can see it in the browser, but when I try to use the interface in my test controller:

use App\Services\FileMakerInterface;

class DevController extends Controller
{
    public function testFmConnect(FileMakerInterface $fm){
        return $fm;
    }
}

我收到错误消息:响应内容必须是实现__toString()的字符串或对象,给定了对象"."

I get the error "The Response content must be a string or object implementing __toString(), "object" given."

我已经浏览了这种绑定的其他示例,但没有发现我做错了什么.

I've looked through other examples of this kind of a binding and I don't see anything that I'm doing wrong.

有什么想法吗?

推荐答案

问题出在您的testFmConnect()控制器操作中.您将直接返回FileMakerInterface实现,但是控制器方法应返回一个响应对象.

The issue is in your testFmConnect() controller action. You’re returning the FileMakerInterface implementation directly, but controller methods should return a response object.

如果您只想查看方法返回的内容,则可以在控制器操作中使用dd()函数:

If you’re just wanting to check what the method is returning, you can use the dd() function in your controller action:

class DevController extends Controller
{
    public function testFmConnect(FileMakerInterface $fm)
    {
        dd($fm);
    }
}

这篇关于错误响应内容必须是实现__toString()的字符串或对象.在服务提供商中绑定时给出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 09:59