Laravel服务提供商绕过

时间:2015-08-01 17:25:01

标签: php dependency-injection laravel-5 ioc-container service-provider

我有以下课程:

<?php

namespace App\CustomClasses;

class Disqus {

    protected $secretKey;
    protected $publicKey;

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

    public function payload()
    {
    ...
    }    

}

我还创建了一个服务提供程序(简化版本),将此类绑定到IOC容器:

<?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()
    {
        //
    }

}

在我的控制器中:

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

问题在于,无论何时我使用$disqus变量,它都不是从服务提供者那里“生成”的,而是来自Disqus类本身。

但是,当我有$disqus = App::make('Disqus');时,变量将通过服务提供商。

所以我的问题是,由于绑定存在于服务提供者中,$disqus变量不应来自 DisqusServiceProvider 而不是 Disqus 类直接在我的控制器中使用它时?

我错过了什么吗?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

当控制器的操作需要传递类 App \ CustomClasses \ Disqus 的对象时,服务容器会在其映射中搜索依赖项的类名,以查看它是否具有相应的服务。但是,它使用完全限定的类名,这就是它在您的情况下无法正常工作的原因。

在您的服务提供商中,您已将服务绑定到 Disqus ,而完全限定的类名称为 App \ CustomClasses \ Disqus 。在提供程序中使用完全限定的类名,它应该可以工作。

相关问题