【发布时间】: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 ]]
谁能告诉我我错过了什么??
【问题讨论】: