简体   繁体   中英

Execute dependency when calling a class in Laravel (IoC Container)

I'm creating a little Google Analytics service by myself to play around and learn how to do this kind of stuff.

So I have a AnalyticsServiceProvider which contains:

public function register()
{
    $this->app->bind('analytics', function () {
        $client = new Google_Client();
        $client->setApplicationName('Hodor Application');
        $client->setAssertionCredentials(new Google_Auth_AssertionCredentials($account, $scope, $key));

        return new AnalyticsService(new Google_Service_Analytics($client));
    });
}

My AnalyticsService has a doSomething() method which will get data from the API.
I've bound the analytics IoC binding to a Analytics facade.

So while that's setup, I can call Analytics::doSomething(); from my controller. Which works fine.

But I want to inject the AnalyticsService into my controller from the constructor.. Like so:

public function __construct(AnalyticsService $service)
{
    $this->service = $service;
}

But, this isn't working because the code from the AnalyticsServiceProvider wont be executed.
Is there any way where I can execute this, upon injecting the AnalyticsService in my constructor?

Make the IoC container key be the actual class name:

public function register()
{
    $this->app->bind('AnalyticsService', function () {
        // register as before...
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM