【问题标题】:Lumen 8 Dependency injection - Unresolvable dependency resolving [Parameter #0 [ <required> $app ]] in class Illuminate\Support\ServiceProviderLumen 8 依赖注入 - 类 Illuminate\Support\ServiceProvider 中无法解析的依赖解析 [Parameter #0 [ <required> $app ]]
【发布时间】:2021-06-12 02:30:45
【问题描述】:

我正在尝试让依赖注入在 Lumen 8 中工作,但我显然遗漏了一些东西。我以为就这么简单...

制作一个要注入的接口(一个接口,以便我以后可以根据需要更改实现)

<?php
namespace App\Interfaces;
use Illuminate\Support\ServiceProvider;

interface TestServiceInterface {
    public function sayHello();
}

然后制作类(接口的一种实现)

<?php

namespace App\Services;
use App\Interfaces\TestServiceInterface;
use Illuminate\Support\ServiceProvider;


class TestService  extends ServiceProvider implements TestServiceInterface
{
    public function sayHello()
    {
        return 'hello';
    }
}

然后将其注入到控制器中

<?php

namespace App\Http\Controllers;
use App\Interfaces\TestServiceInterface;

class TestsController extends Controller
{
    protected $testService;

    public function __construct(TestServiceInterface $testService)
    {
        //The route rejects requests without token and adds currentUser to request
        $this->testService = $testService;  
    }

    public function useTheSerive()
    {
        return $this->testService->sayHello();
    }

}

从我读过的内容来看,听起来需要绑定才能让系统知道什么类与什么接口相关。我把这行放在ApplicationProvider.php的注册函数里

 $this->app->bind(TestServiceInterface::class, TestService::class);

我一定还是遗漏了一些东西,因为我收到了错误

类 Illuminate\Support\ServiceProvider 中无法解析的依赖解析 [Parameter #0 [ $app ]]

谁能告诉我我错过了什么??

【问题讨论】:

    标签: php laravel lumen


    【解决方案1】:

    显然这是 Lumen 与 Laravel 不同的例子之一。

    当您进行绑定时,您还必须将 $app 注入到具体类中。

    $this->app->bind(TestServiceInterface::class, function($app) {
            return new TestService($app);
        });
    

    我添加了注册服务提供商的那一行 (Providers\AppServiceProviders,php),它现在可以工作了。

    【讨论】:

      猜你喜欢
      • 2019-05-25
      • 2019-04-23
      • 2014-07-30
      • 2022-01-25
      • 2019-08-23
      • 2021-07-21
      • 2018-05-11
      • 1970-01-01
      • 2015-12-25
      相关资源
      最近更新 更多