Symfony 3.3 - Services.yml参数(ResponseFactory) - 参数以字符串而不是对象的形式传递

时间:2018-02-01 23:43:45

标签: php symfony dependency-injection factory subscriber

错误

您好,我收到以下错误:

Type error: Argument 2 passed to ApiExceptionBundle\EventListener\ApiExceptionSubscriber::__construct() must implement interface ApiExceptionBundle\Component\Factory\ResponseFactoryInterface, string given, called in C:\htdocs\projects\myproject\var\cache\dev\appDevDebugProjectContainer.php on line 4293

显示正在传递的参数类型不正确的调用堆栈

从调用堆栈中可以看出,第二个参数是一个字符串。 (但它实际上应该是一个实例化该类型的对象)。

at ApiExceptionSubscriber->__construct(true, 'ApiExceptionBundle\\Component\\Factory\\ResponseFactoryInterface', true, array('/admin/'))
in appDevDebugProjectContainer.php (line 4293)

构造函数定义

订阅者位于 myproject \ src \ ApiExceptionBundle \ EventListener \ ApiExceptionSubscriber.php ,其构造函数定义如下:

public function __construct($debug, ResponseFactoryInterface $responseFactory, $enabled = true, $excludedPaths = [])

(请注意,它需要 ResponseFactoryInterface 对象而不是字符串。)

Services.yml条目

myproject / src / ApiExceptionBundle / Resources / config / services.yml 中,相关条目如下:

ApiExceptionBundle\EventListener\ApiExceptionSubscriber:
        arguments:
            $responseFactory: 'ApiExceptionBundle\Component\Factory\ResponseFactoryInterface'

我试过的其他事情

从我使用的原始示例中,我发现在服务中 $ responseFactory 参数分配的开头实际上存在 @ symbol 。 yml 文件。

我使用的原始代码作为示例,具有与此类似的 services.yml 条目:

$responseFactory: '@ApiExceptionBundle\Component\Factory\ResponseFactoryInterface'

不幸的是,当我尝试在我的代码中添加 @ symbol 时(如上所述),它给了我这个错误:

PHP Fatal error:  Uncaught Symfony\Component\DependencyInjection\Exception\RuntimeException: Cannot dump de
finition because of invalid class name ('@ApiExceptionBundle\\Component\\Factory\\ResponseFactory') in C:\h
tdocs\projects\myproject\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Dumper\PhpDumper.ph
p:1568

问题

所以,我有两个问题:

  1. 我做错了什么? (我假设这是我在services.yml中引用的方式)。
  2. @符号有什么作用?猜测一下,我认为它告诉代码实例化引用类的对象而不是字面上使用字符串。这是对的吗?

1 个答案:

答案 0 :(得分:0)

Symfony 3.3 +

您似乎正在尝试传递接口。应该使用特定的实例。

您是否尝试使用别名进行自动装配?

# services.yml

services:
    ApiExceptionBundle\YourResponseFactory: ~
    ApiExceptionBundle\Component\Factory\ResponseFactoryInterface:
        alias: ApiExceptionBundle\YourResponseFactory

    ApiExceptionBundle\EventListener\ApiExceptionSubscriber:
        autowire: true

使用PSR-4自动发现

或者您可以使用PSR-4 autodiscovery

# services.yml

services:
    _defaults:
        autowire: true

    ApiExceptionBundle\: ~
        resource: ../ # path to ApiExceptionBundle directory

    ApiExceptionBundle\Component\Factory\ResponseFactoryInterface:
        alias: ApiExceptionBundle\YourResponseFactory

Symfony 3.4 +

由于 Symfony 3.4 ,您可以通过single-services from your code的自动候选来省略别名。

# services.yml

services:
    _defaults:
        autowire: true

    ApiExceptionBundle\: ~
        resource: ../ # path to ApiExceptionBundle directory
相关问题