YAML and symfony2


YAML and symfony2

我注意到在symfony2的config.yml文件中,导入功能如下所示

imports:
- { resource: security.yml }
- { resource: services.yml }

我正在使用我自己的捆绑包中的一些YAML文件来初始化一些只读实体。然而,它们都被挤在这个单一的YAML文件中。我正在使用Symfony'Component'Yaml'Parser;组件来读取此文件。

然而,如果我试图复制import的这个好特性,解析器只正常读取它,它不会解释import和resource关键字。

imports:
- { resource: test.yml }

也就是说,var_dump只是一个没有解释的节点树。未加载测试。

如何使用与config.yml文件中相同的功能?

正如Anthon所建议的,我使用一些symfony组件创建了自己的实现,这是为感兴趣的人提供的类(这是一个基本的实现,可以用它做任何你想做的事情)

use Symfony'Component'Yaml'Parser;
use Symfony'Component'Filesystem'Filesystem;
class MyYmlParser {
protected $parser;
protected $finder;
protected $currentDir;
protected $ymlPath;
protected $data;
public function __construct($rootDir) {
    $this->rootDir = $rootDir;
    $this->parser = new Parser();
    $this->fs = new Filesystem;
}
public function setYmlPath($ymlPath) {
    $this->ymlPath = $ymlPath;
    $this->currentDir = dirname($this->ymlPath) . "/";
    return $this;
}
public function getYmlPath() {
    return $this->ymlPath;
}
private function parseFile($path) {
    if ($this->fs->exists($path)):
        return $this->parser->parse(file_get_contents($path));
    else:
        throw new 'Exception("$path Do not exsist");
    endif;
}
private function buildPathFromImport($fileName) {
    return $this->currentDir . $fileName;
}
public function parse($ymlPath) {
    $this->setYmlPath($ymlPath);
    $this->data = $this->parseFile($this->ymlPath);
    if (isset($this->data["imports"])):
        foreach ($this->data["imports"] as $array):
            $importData = $this->parseFile($this->buildPathFromImport($array["resource"]));
            $this->data = array_merge($this->data, $importData);
        endforeach;
        unset($this->data['imports']);
    endif;
    #dump($this->data); exit();
    return $this->data;
}
}

用法很简单:

//Follow symfony syntax for imports that is:
 imports:
  - { resource: test.yml }
  - { resource: nested/dir/test2.yml }
$myYmlParser = new MyYmlParser();
$parsedData = $myYmlParser->parse($path); //the path to your yml file
//thats it, you got an array with the data form other files and the original file.
 //dont forget to add it to your services for the rootDir
 AmceBundle.ymlParser:
    class: OP'AcmeBundle'Services'MyYmlParser
    arguments: ["%kernel.root_dir%"]

YAML解析器在所有情况下都能正常读取它。仅对于config.yml,处理所代表实例的程序通过从作为关联值的列表中提取并用与resource关联的值替换节点来"扩展"映射关键字import的值。

这不是YAML的一个特性,而是对解析器传递给程序的数据的解释。如果你的程序没有递归地应用这个功能,你应该对程序进行修补