我想制作一个本地配置文件,config_local.yml它允许正确配置每个开发环境,而不会搞砸其他人的开发环境.我希望它是一个单独的文件,以便我可以"gitignore"它,并知道项目中没有任何必要的东西,同时没有git的问题经常告诉我config_dev.yml有新的变化(并运行风险)有人做出这些改变).
现在,我有config_dev.yml在做
imports:
- { resource: config_local.yml }
Run Code Online (Sandbox Code Playgroud)
这很好,除非文件不存在(即对于存储库的新克隆).
我的问题是:有没有办法让这包括可选的?即,如果文件存在则导入它,否则忽略它.
编辑:我希望语法如下:
imports:
- { resource: config.yml }
? { resource: config_local.yml }
Run Code Online (Sandbox Code Playgroud)
Kri*_*ris 23
我知道这是一个非常古老的问题,我确实认为批准的解决方案更好我认为我会提供一个更简单的解决方案,它具有不更改任何代码的好处
您可以使用ignore_errors选项,如果该文件不存在,则不会显示任何错误
imports:
- { resource: config_local.yml, ignore_errors: true }
Run Code Online (Sandbox Code Playgroud)
警告,如果文件中有语法错误,也会被忽略,因此如果您有意外结果,请检查以确保文件中没有语法错误或其他错误.
小智 16
还有另一种选择.
在app/appKernel.php上将registerContainerConfiguration方法更改为:
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
$extrafiles = array (
__DIR__.'/config/config_local.yml',
);
foreach ($extrafiles as $filename) {
if (file_exists($filename) && is_readable($filename)) {
$loader->load($filename);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样你就有了一个覆盖config_env.yml文件的全局config_local.yml文件
解决方案是创建一个单独的环境,在Symfony2 cookbook中对此进行了解释.如果您不想创建一个,则还有另一种方法涉及创建扩展.
// src/Acme/Bundle/AcmeDemo/DepencendyInjection/AcmeDemoExtension.php
namespace Acme\DemoBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class AcmeDemoExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
// All following files will be loaded from the configuration directory
// of your bundle. You may change the location to /app/ of course.
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
try
{
$loader->load('config_local.yml');
}
catch(\InvalidArgumentException $e)
{
// File was not found
}
}
}
Run Code Online (Sandbox Code Playgroud)
Symfony代码中的一些挖掘显示,如果找不到文件,将抛出.它被调用.YamlFileLoader::load()FileLocator::locate()\InvalidArgumentExceptionYamlFileLoader::load()
如果使用命名约定,则会自动执行扩展.有关更全面的说明,请访问此博客.
| 归档时间: |
|
| 查看次数: |
7783 次 |
| 最近记录: |