如何使用Treebuilder在无Bundleless应用程序中加载自定义配置文件



我正在尝试导入一个名为test.yaml.的自定义配置文件

我把test.yaml放在config/packages/local文件夹和config/packings文件夹中。

test.yaml文件如下所示:

# config/packages/test.yaml
test1: 'hello'

当我编译应用程序时,我得到这样的错误:;没有任何扩展能够加载"0"的配置;test1";

现在你要告诉我,我需要创造,扩展和blabla。但我想不通。有没有一种方法可以在不创建Bundle的情况下创建扩展。我在文档中找不到任何关于Bundle范围之外的Extension的例子。我的意思是我想在src文件夹中创建它?

一个相关的问题是:如果我像本例中那样设置TreeBuilder:https://symfony.com/doc/current/components/config/definition.html

有可能避免创建扩展吗?

Symfony版本为5.1。

似乎几个月前我看到了一个类似的问题,但找不到。src/Kernel类充当AppBundle类,允许您执行注册扩展等操作。

# src/Kernel.php
class Kernel extends BaseKernel
{
use MicroKernelTrait;
protected function prepareContainer(ContainerBuilder $container)
{
$container->registerExtension(new TestExtension());
parent::prepareContainer($container);
}
...
# src/TestExtension.php
class TestExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
// TODO: Implement load() method.
dump($configs);
}
}

至于在没有扩展的情况下处理树生成器,我不知道这是否可能。配置的东西已经足够复杂了,所以我不会自己去那里。

有点偏离主题,我找不到在Kernel中使用prepareContainer的实际案例。源代码清楚地表明,上面显示的方法是可行的。

大多数时候,应用程序特定的配置只是在config目录中完成的。捆绑包配置系统的要点是允许应用程序覆盖默认的捆绑包配置。我真的没有看到应用程序级别扩展的意义。什么会覆盖它?也许是某种复杂的数据库驱动的树生成器?似乎不太可能。

这可能是一种情况,仅仅因为你能做某事并不意味着你应该做。

对于自定义配置文件,我认为您可能需要在顶部添加参数,如

# config/packages/test.yaml
parameters:
test1: hello

https://symfony.com/doc/current/configuration.html#configuration-参数

我有一个类似的用例,但对于每个环境应用程序级别的配置,我不想编译到容器中。我最终只使用了序列化程序组件并从./config/static:加载文件

<?php
declare(strict_types=1);
namespace AppUtility;
use SymfonyComponentConfigFileLocator;
use SymfonyComponentSerializerEncoderYamlEncoder;
use SymfonyComponentSerializerNormalizerArrayDenormalizer;
use SymfonyComponentSerializerNormalizerBackedEnumNormalizer;
use SymfonyComponentSerializerNormalizerDateTimeNormalizer;
use SymfonyComponentSerializerNormalizerObjectNormalizer;
use SymfonyComponentSerializerSerializer;
use SymfonyComponentYamlYaml;
class CustomConfigurationLoader {
private array $staticCache;
public function __construct(
private readonly string $appEnv,
private readonly string $projectRoot,
) {
}
public function load(string $configurationName, string $type): mixed {
if (isset($this->staticCache[$configurationName])) {
return $this->staticCache[$configurationName];
}
$candidatePaths = [
"{$this->projectRoot}/config/custom/{$this->appEnv}",
"{$this->projectRoot}/config/custom",
];
$configLocator = new FileLocator($candidatePaths);
$data = Yaml::parse(file_get_contents($configLocator->locate("{$configurationName}.yaml")));
$serializer = new Serializer([
new ArrayDenormalizer(),
new BackedEnumNormalizer(),
new DateTimeNormalizer(['datetime_timezone' => 'UTC', 'datetime_format' => 'U']),
new ObjectNormalizer(),
], [new YamlEncoder()]);
$this->staticCache[$configurationName] = $serializer->denormalize($data, $type, 'yaml');
return $this->staticCache[$configurationName];
}
}

最新更新