Symfony 结合 yaml 和 php 配置文件

Symfony combine yaml and php configuration files

在 Symfony 4 中,我想为服务组合不同的配置文件。在以下场景中,我尝试从名为 services.php 的 php 配置导入服务,然后在导入其他服务的 yaml 文件中执行其他服务配置..

services.yaml

imports:
    - { resource: services.php }


services:

    _defaults:
        autowire: true      
        autoconfigure: true 
        public: false    

    App\:
        resource: '../src/*'
        exclude: '../src/{Entity,Migrations,Tests,Kernel.php}'

services.php

<?php

use Symfony\Component\DependencyInjection\Definition;

$definition = new Definition();

$definition
    ->setAutowired(true)
    ->setAutoconfigured(true)
    ->setPublic(false)
;

$this->registerClasses($definition, 'App\', '../src/*', '../src/{Entity,Migrations,Tests}');

$container->getDefinition(\App\SomeClass::class)
    ->setArgument('$param', 'someValue');

Class 文件

class SomeClass
{
    public function __construct(string $param)
    {
         ...
    }

我收到以下错误:

Cannot autowire service "App\SomeClass": argument "$param" of method "__construct()" is type-hinted "string", you should configure its value explicitly.

另外,我想知道我是否必须从 yaml 覆盖初始的 _defaults 定义(或其他已经由导入的文件完成的定义)或者我可以继承。不确定这些文件是如何合并的。

问题是您在 src/* 中注册了 classes 两次,一次在您的 services.php 中,一次在您的 services.yaml.

因此,在第一个 运行 和 services.php 中,您正确定义了 class 和所需的参数,然后在第二个 运行 和 services.yaml 中定义被覆盖,它又失去了争论。

最小的解决方案是在 services.yaml 中排除 SomeClass.php,这样它就不会被第二次注册:

App\:
    resource: '../src/*'
    exclude: '../src/{Entity,Migrations,Tests,Kernel.php,SomeClass.php}' # <- here I added SomeClass.php

创建一个单独的命名空间并在 YAML 中排除该目录并仅在 PHP-config 中注册该目录会更好。