首页 文章

如何使用PHP-DI Symfony Bridge作为控制器?

提问于
浏览
1

我想使用我最近设置的PHP-DI 6和PHP-DI Symfony Bridge 3的Symfony 4项目 .

我的 project structure 看起来像这样:

|-config
|---dependencies
|-----common.php
...
|-src
...
|-Interop
|---Api
|---Website
|-----Controller
|-------IndexController.php
...
|---Services
|-----Dummy
|-------FooService.php
|-------FooServiceInterface.php
...
|-Kernel.php

FooServiceBuzService 实现 FooServiceInterface .

/config/dependencies/common.php

return [
    IndexController::class => DI\create(IndexController::class),
    FooServiceInterface::class => DI\create(FooService::class),
];

IndexController 获取了 FooServiceInterface 注入的实例 .

public function __construct(FooServiceInterface $fooService)
{
    $this->fooService = $fooService;
}

Kernel 扩展了 DI\Bridge\Symfony\Kernel 并实现了 buildPHPDIContainer(...)

protected function buildPHPDIContainer(PhpDiContainerBuilder $builder)
{
    $builder->addDefinitions(__DIR__ . '/../config/dependencies/common.php');
    return $builder->build();
}

Everythings似乎根据PHP-DI Symfony Bridge documentation设置 .

如果 FooServiceInterface 只有一个实现,那么一切正常 . 但是当我再添加一个时,例如:

class BuzService implements FooServiceInterface

我收到一个错误:

RuntimeException无法自动装配服务“App \ Interop \ Website \ Controller \ IndexController”:方法“__construct()”的参数“$ fooService”引用接口“App \ Services \ Dummy \ FooServiceInterface”但不存在此类服务 . 您应该将此接口别名为其中一个现有服务:“App \ Services \ Dummy \ BuzService”,“App \ Services \ Dummy \ FooService” . 你创建了一个实现这个接口的类吗?

Why am I getting this error & how to get this structure working correctly?

1 回答

  • 2

    此错误消息看起来像Symfony错误消息,而不是PHP-DI错误消息 .

    我猜Symfony扫描所有类的自动装配,包括你的控制器(即使没有必要) .

    这是我第一次听到这个,我想你需要完全禁用Symfony的自动装配,还是某些特定的文件夹?如果您可以向PHP-DI的文档发送拉取请求,这将是非常棒的:)

相关问题