我正在尝试在非 Symfony 项目中实现 Symfony 依赖注入组件 ( https://symfony.com/doc/current/components/dependency_injection.html ) 。
如果我将所有服务和参数放入一个“services.yaml”文件中,效果会很好。前任:
# services.yaml
parameters:
mysql.host: "127.0.0.1"
mysql.database: "database"
mysql.username: "root"
mysql.password: ""
oracle.database: ""
oracle.username: ""
oracle.password: ""
cookie.domain: ".site.local"
cookie.lifetime: 0
cookie.useHttps: true
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
OtherNamespace\:
resource: '../someHomemadeLibrary/src/*'
OtherNamespace\Database\Drivers\MySqlDriver:
class: OtherNamespace\Database\Drivers\MySqlDriver
arguments:
$host: "%mysql.host%"
$database: "%mysql.database%"
$username: "%mysql.username%"
$password: "%mysql.password%"
# ...
由于文件变得非常大,我想将其拆分为不同的文件,如下所述:https ://symfony.com/doc/current/service_container/import.html#importing-configuration-with-imports
所以我尝试了:
# index.php
$containerBuilder = new ContainerBuilder();
$loader = new YamlFileLoader($containerBuilder, new FileLocator('config/'));
$loader->load('services.yaml');
# services.yaml
imports:
- { resource: "databases.yaml" }
- { resource: "sessions.yaml" }
services:
_defaults:
autowire: true
autoconfigure: true
App\:
resource: '../src/*'
exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'
OtherNamespace\:
resource: '../someHomemadeLibrary/src/*'
# databases.yaml
parameters:
mysql.host: "127.0.0.1"
mysql.database: "database"
mysql.username: "root"
mysql.password: ""
services:
OtherNamespace\Database\Drivers\MySqlDriver:
class: OtherNamespace\Database\Drivers\MySqlDriver
arguments:
$host: "%mysql.host%"
$database: "%mysql.database%"
$username: "%mysql.username%"
$password: "%mysql.password%"
# ...
但是在这种配置中,我收到以下错误:
致命错误:未捕获的 Symfony\Component\DependencyInjection\Exception\RuntimeException:无法自动装配服务“OtherNamespace\Database\Drivers\MySqlDriver”:方法“__construct()”的参数“$host”是类型提示的“字符串”,您应该配置它的价值明确。
如果我切换导入顺序,那么是CookieSession有问题。就像导入覆盖参数和服务只使用最后一个?如何将我的服务及其参数拆分到多个文件中?
谢谢 !