Lumen 8 依赖注入 - 无法解析的依赖解析类 Illuminate\Support\ServiceProvider 中的 [Parameter #0 [ <required> $app ]]

时间:2021-03-14 17:32:50

标签: php laravel lumen

我正在尝试在 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 ]]

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

1 个答案:

答案 0 :(得分:0)

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

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

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

我在注册我的服务提供者的地方添加了那行 (Providers\AppServiceProviders,php),现在它正在工作。