首页 文章

无法在Symfony 3.3中将参数传递给服务

提问于
浏览
5

我在Symfony 3.3的服务中使用了一个参数,但我一直收到错误 .

Error

[Symfony \ Component \ DependencyInjection \ Exception \ AutowiringFailedException]无法自动装配服务“AppBundle \ Service \ ApiInterface”:方法“__construct()”的参数“$ api_endpoint”必须具有类型提示或显式赋予值 .

config.yml

services:
app.security.login_form_authenticator:
    class: AppBundle\Security\LoginFormAuthenticator
    autowire: true
    arguments: ['@doctrine.orm.entity_manager']
app.service.api_interface:
    class: AppBundle\Service\ApiInterface
    arguments:
      $api_endpoint: "%endpoint test%"

_defaults:
    autowire: true
    autoconfigure: true
    public: false

AppBundle\:
    resource: '../../src/AppBundle/*'
    exclude: '../../src/AppBundle/{Entity,Repository,Tests}'

AppBundle\Controller\:
    resource: '../../src/AppBundle/Controller'
    public: true
    tags: ['controller.service_arguments']

ApiInterface.php

use Unirest;

class ApiInterface
{

private $api_endpoint;

public function __construct(string $api_endpoint)
{
    $this->timeout = 1;

    echo 'form apiinterface construct: ' . $api_endpoint;

}

感谢任何帮助我觉得我应该在一个简单的工作中绕圈子!

1 回答

  • 4

    问题是你有2种不同的服务: app.service.api_interfaceAppBundle\Service\ApiInterface . 第一个是好配置,第二个不是 .

    如果您一定需要 app.service.api_interface 服务,您可以更改您的配置,以便将第一个作为第二个的别名,如下所示:

    app.service.api_interface: '@AppBundle\Service\ApiInterface'
    AppBundle\Service\ApiInterface:
        arguments:
            $api_endpoint: "%endpoint test%"
    

    使用您的配置,您不配置 AppBundle\Service\ApiInterface 服务,但配置 app.service.api_interface 服务 . 根据我的建议,您配置2个服务 .

    如果您不需要 app.service.api_interface 服务,则只能提供一项服务:

    AppBundle\Service\ApiInterface:
        arguments:
            $api_endpoint: "%endpoint test%"
    

    此声明会覆盖 AppBundle\Service\ApiInterface 服务 . 您可以覆盖's imported by using its id (class name) below : It'更喜欢的任何服务,以便将此覆盖移到 AppBundle\ 声明下方 .

    最终文件可以是这样的:

    #app/config/services.yml
    services:
        _defaults:
            autowire: true
            autoconfigure: true
            public: false
    
        AppBundle\:
            resource: '../../src/AppBundle/*'
            exclude: '../../src/AppBundle/{Entity,Repository,Tests}'
    
        AppBundle\Controller\:
            resource: '../../src/AppBundle/Controller'
            public: true
            tags: ['controller.service_arguments']
    
        app.security.login_form_authenticator: '@AppBundle\Security\LoginFormAuthenticator'
            # autowire: true #Optional, already set in _defaults
            # arguments: ['@doctrine.orm.entity_manager'] # Optional because of autowiring
    
        app.service.api_interface: '@AppBundle\Service\ApiInterface' 
        AppBundle\Service\ApiInterface:
            arguments:
                $api_endpoint: "%endpoint test%"
    

    Documentation : manually wiring arguments

    Documentation : explicitly configuring services and arguments

    另外,我建议你删除参数名称 %endpoint test% 的空格(例如将其重命名为 %endpoint_test%

相关问题