YAML和symfony2

时间:2015-07-02 00:06:40

标签: php symfony yaml

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

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

我在自己的bundle中使用了一些YAML文件来初始化一些只读实体。但是,它们都是在这一个YAML文件中包装好的。我正在使用Symfony\Component\Yaml\Parser;组件来读取此文件。

但是,如果我尝试复制import的这个很好的特性,解析器只能正常读取它并且它不解释import或resource关键字。

imports:
- { resource: test.yml }

这就是var_dump只是没有解释的节点树。未加载测试。

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

2 个答案:

答案 0 :(得分:1)

正如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%"]

答案 1 :(得分:0)

YAML解析器在所有情况下都能正常读取它。仅对于config.yml程序处理,所表示的实例通过从作为关联值的列表中取出并用与{{{{}相关联的值替换节点来“展开”映射键import的值。 1}}。

这不是YAML的功能,而是对解析器传递给程序的数据的解释。如果您的程序没有递归地应用此功能,则应修改程序以执行此操作。