Search code examples
phpdependency-injectionlaravel-5ioc-containerservice-provider

Laravel Service Provider bypassed


I have the following Class:

<?php

namespace App\CustomClasses;

class Disqus {

    protected $secretKey;
    protected $publicKey;

    public function __construct()
    {
        $this->secretKey = 'abc';
        $this->publicKey = '123';
    }

    public function payload()
    {
    ...
    }    

}

I have also created a Service Provider (simplified bellow), to bind this class to the IOC container:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\CustomClasses\Disqus;

class DisqusServiceProvider extends ServiceProvider {

    public function register()
    {
        $this->app->singleton('Disqus', function() {
            return new Disqus();
        });
    }

    public function boot()
    {
        //
    }

}

And in my controller:

<?php

use App\CustomClasses\Disqus;

class ArticlesController extends Controller {

    public function view(Disqus $disqus)
    {
    ...
    //$disqus = App::make('Disqus');
    return View::make('articles.view', compact(array('disqus')));
    }
}

The problem is that whenever I use the $disqus variable, it is not 'generated' from the Service Provider, but the Disqus class itself.

However, when I have $disqus = App::make('Disqus');, the variable goes through the service provider.

So my question is, since the binding exists in the Service Provider, shouldn't the $disqus variable come from the DisqusServiceProvider rather than the Disqus class directly when I use it in my controller?

Am I missing something?

Thanks in advance for any help.


Solution

  • When the controller's action requires an object of class App\CustomClasses\Disqus to be passed, the service container searches its mappings for the class name of the dependency to see if it has the corresponding service. However, it uses the fully qualified class name and this is the reason it doesn't work correctly in your case.

    In your service provider you have bound the service to Disqus, while the fully qualified class name is App\CustomClasses\Disqus. Use the fully qualified class name in the provider and it should work.