错误响应内容必须是一个字符串或对象实现 __toString(), "object" 在服务提供者中绑定时给出

Error The Response content must be a string or object implementing __toString(), "object" given when binding in service provider

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

我的混凝土class

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 在具体的 class' 构造函数中,我可以在浏览器中看到它,但是当我尝试在我的测试控制器中使用该接口时:

use App\Services\FileMakerInterface;

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

我收到错误 "The Response content must be a string or object implementing __toString(), "object" given."

我查看了此类绑定的其他示例,但没有发现我做错了什么。

有什么想法吗?

问题出在您的 testFmConnect() 控制器操作中。您正在 return 直接执行 FileMakerInterface 实现,但是控制器方法应该 return 一个响应对象。

如果您只是想检查方法是什么 returning,您可以在控制器操作中使用 dd() 函数:

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