【问题标题】:Can`t instantiate class using IOC contatiner laravel无法使用 IOC 容器 laravel 实例化类
【发布时间】:2018-05-24 17:05:08
【问题描述】:

我正在尝试使用依赖注入来实例化我的课程。 这个类有自己的服务提供者,在 app.php 中注册

 class Something
 {
      private $variable;

      public function __construct(string $variable)
      {
          $this->variable = $variable; 
      }
 }

这是服务提供商

class SomethingServiceProvider extends ServiceProvider
{

    public function boot()
    {

    }


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

当我尝试在控制器中使用此类实例时...

class TestController extends AppBaseController
{
    public function __construct(Something $something)
    {
        $this->something = $something;
    }
...

我收到错误:

"无法解析的依赖解析[参数#0 [字符串$variable]] 在课堂上 Container->unresolvablePrimitive(object(ReflectionParameter)) in Container.php(第 848 行)“

【问题讨论】:

  • 除了其他答案,一定要在你的config/app.php中添加这个服务提供者,这样才能加载

标签: php laravel ioc-container


【解决方案1】:

我猜YourServiceProvider::__construct 接受一个非类型化的$app 实例。这意味着 Laravel 无法自动解决它。尝试输入它; public function __construct(Application $app) 带有正确的使用语句。

更多:https://laravel.com/docs/5.3/container#automatic-injection

【讨论】:

  • 不确定我在这里缺少什么。服务提供者中没有构造函数
【解决方案2】:

当你注册要注入的东西时,你需要使用完全限定的类名:

public function register()
{
    $this->app->singleton(Something::class, function () {
        return new Something( 'test');
    });
}

否则 Laravel 将尝试自动注入一些东西,这意味着它将首先尝试注入 Something 的依赖项,然后确定这是一个字符串并失败。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    • 2014-10-08
    相关资源
    最近更新 更多