-->

Error The Response content must be a string or obj

2019-07-09 12:32发布

问题:

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

My concrete 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'];
    } 
}

My interface

namespace App\Services;

interface FileMakerInterface {

} 

My service provider

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'));
        });
    }
}

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;
    }
}

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.

Any ideas?

回答1:

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

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);
    }
}