我在Symfony 3.3的服务中使用了一个参数,但我一直收到错误.
错误
[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']
Run Code Online (Sandbox Code Playgroud)
ApiInterface.php
use Unirest;
class ApiInterface
{
private $api_endpoint;
public function __construct(string $api_endpoint)
{
$this->timeout = 1;
echo 'form apiinterface construct: ' . $api_endpoint;
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示感觉我会围成一圈,这应该是一个简单的工作!
问题是您有两种不同的服务:app.service.api_interface和AppBundle\Service\ApiInterface 。第一个配置好,第二个则不好。
如果您必须需要该app.service.api_interface服务,您可以更改您的配置,以便将第一个服务作为第二个服务的别名,如下所示:
app.service.api_interface: '@AppBundle\Service\ApiInterface'
AppBundle\Service\ApiInterface:
arguments:
$api_endpoint: "%endpoint test%"
Run Code Online (Sandbox Code Playgroud)
使用您的配置,您不是配置AppBundle\Service\ApiInterface服务,而是配置app.service.api_interface服务。根据我的建议,您配置了这 2 个服务。
如果您不需要app.service.api_interface服务,您只能委托一项服务:
AppBundle\Service\ApiInterface:
arguments:
$api_endpoint: "%endpoint test%"
Run Code Online (Sandbox Code Playgroud)
该声明会覆盖该AppBundle\Service\ApiInterface服务。您可以使用下面的 id(类名)覆盖任何导入的服务:最好将此覆盖移动到声明下方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%"
Run Code Online (Sandbox Code Playgroud)
另外,我建议你把参数名的空格去掉%endpoint test%(重命名为%endpoint_test%例如)