代码之家  ›  专栏  ›  技术社区  ›  Ilias Kouroudis

绕过Laravel服务提供商

  •  1
  • Ilias Kouroudis  · 技术社区  · 10 年前

    我有以下课程:

    <?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(美元) 变量来自 DisqusService提供程序 而不是 Disqus公司 当我在我的控制器中使用它时,直接使用它?

    我错过了什么吗?

    提前感谢您的帮助。

    1 回复  |  直到 10 年前
        1
  •  1
  •   jedrzej.kurylo    10 年前

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

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

    推荐文章