Symfony 4 中的外部服务配置 [英] External service configuration in Symfony 4
问题描述
我正在尝试使用 services.yaml 中的导入将一些服务定义移动到单独的文件中.您可以在 symfony 文档中找到此内容.
I'm trying to use imports in services.yaml to move some services definitions to separate file. Here you can find this in symfony doc.
但是当我尝试执行此操作时出现错误:
But when i'm trying to do this I'm getting an error:
无法自动装配服务App\Domain\Test\Test":方法__construct()"的参数$param"必须具有类型提示或明确给出一个值.
Cannot autowire service "App\Domain\Test\Test": argument "$param" of method "__construct()" must have a type-hint or be given a value explicitly.
这是我的配置文件:
# services.yaml
imports:
- { resource: services/test.yaml }
services:
_defaults:
autowire: true
autoconfigure: true
public: false
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'
App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']
和
# test.yaml
parameters:
param: 'some param'
services:
App\Domain\Test\Test:
public: true
autowire: true
arguments:
$param: '%param%'
这里是服务:
namespace App\Domain\Test;
class Test
{
private $mailer;
private $param;
public function __construct(\Swift_Mailer $mailer, string $param)
{
$this->mailer = $mailer;
$this->param = $param;
}
}
如果我将参数和服务移动到 services.yaml 中,这将运行良好.有人知道我做错了什么吗?
This is working well if I move parameters and service into services.yaml. Do somebody know what I'm doing wrong?
推荐答案
问题是您的第一个文件尝试将您的服务加载为服务,并且无法自动填充参数 string $param
.
The problem is that your first file try to load as service your service and can't fill automatically the parameter string $param
.
一个好的解决方法可能是排除您的服务:
A good fix may be to exclude your service:
services:
App\:
resource: '../src/*'
exclude: '../src/{Entity,Migrations,Tests,Kernel.php,Domain/Test.php}'
另一种解决方案是简单地将此定义放在 services.yaml
文件中.
Another solution is to simply put this definition inside the services.yaml
file.
您也可以考虑加载 App\Something\:
而不是完整的命名空间,但如果您尝试在跨命名空间定义中自动装配,这会带来缺点.(某些功能可能无法按预期工作)
You may also consider to load App\Something\:
instead of the complete namespace but this has drawbacks if you try to autowire in cross-namespaces definitions. (some features may not work as expected)
这篇关于Symfony 4 中的外部服务配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!