bwrigley
5 days ago
116
12
Laravel

Binding Interface to service container not resolving in constructor

Posted 5 days ago by bwrigley

Hello. I'm sure I'm doing something dumb here and not understanding the docs properly.

I'm trying to write some classes to manage reporting over the Google Analytics API, but want to make sure I can swap it out later if needs be.

So I have my interface:

namespace App\Contracts;


interface AnalyticsClient
{

    public function run();
    public function buildQuery();
    // etc
}

And I have a Google Analytics class which implements this:

namespace App\Services;

use App\Contracts\AnalyticsClient;

class GoogleAnalyticsClient implements AnalyticsClient
{

    public function run()
    {
        //
    }

    public function buildQuery()
    {
        //
    }
}

And a service provider:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class ReportServiceProvider extends ServiceProvider
{

    public function register()
    {
        $this->app->bind(
            '/App/Contracts/AnalyticsClient',
            '/App/Services//GoogleAnalyticsClient'
        );
    }
}

...which is registered in app.php

'providers' => [
    
    //,

    App\Providers\ReportServiceProvider::class,

So my expectation is now that I can just call am analytics client into existence in my report classes:

namespace App\Reports;

use App\Contracts\AnalyticsClient;

class ProfileViewReport
{

    private $analyticsClient;

    public function __construct(AnalyticsClient $analyticsClient)
    {
        $this->analyticsClient = $analyticsClient;
    }

But sadly, when I run this in tinker:

TypeError: Too few arguments to function App/Reports/ProfileViewReport::__construct(), 0 passed in

I suspect I need to do something else to enable the Analytics client to be created implicitly?

Thank you in advance for helping with this.

Please sign in or create an account to participate in this conversation.