Test fixtures, configuration files, and log files all need to be both human and machine readable. YAML (YAML Ain’t Markup Language) is a less-verbose data serialization format than XML and has become a popular format among software developers mainly because it is human-readable. YAML files are simply text files that contain data written according to YAML syntax rules and usually have a .yml file extension. In this article, you will learn the basics of YAML and how you can integrate a PHP YAML parser into your projects.
测试装置,配置文件和日志文件都必须是人类和机器可读的。 与XML相比,YAML(YAML不是标记语言)是一种不太冗长的数据序列化格式,并且由于它易于阅读,因此已成为软件开发人员中的流行格式。 YAML文件是简单的文本文件,其中包含根据YAML语法规则编写的数据,并且通常具有.yml文件扩展名。 在本文中,您将学习YAML的基础知识以及如何将PHP YAML解析器集成到项目中。
YAML supports advanced features like references and custom data types, but as a PHP developer, most of the time you’ll be interested in how YAML represents enumerated arrays (sequences in YAML terminology) and associative arrays (mappings).
YAML支持引用和自定义数据类型等高级功能,但是作为PHP开发人员,大多数时候您会对YAML如何表示枚举数组(YAML术语中的序列)和关联数组(映射)感兴趣。
The following is how to represent an enumerated array in YAML:
以下是如何在YAML中表示枚举数组:
- 2 - "William O'Neil" - falseEach element of the array is presented after a hyphen and a space. It’s syntax for representing values is similar to that of PHP (quoting strings, etc.)
数组的每个元素都在连字符和空格之后显示。 表示值的语法与PHP相似(引用字符串等)
The above is equivalent to the following PHP:
以上等同于以下PHP:
<?php array(2, "William O'Neil", false);Generally, each element will appear on it’s own line in YAML, but enumerated arrays can also be expressed on a single line using brackets:
通常,每个元素都将在YAML中单独显示在一行上,但是枚举数组也可以使用括号在一行上表示:
[ 2, "William O'Neil", false ]The following code shows how to represent an associative array in YAML:
以下代码显示了如何在YAML中表示关联数组:
id: 2 name: "William O'Neil" isActive: falseFirst the element’s key is stated followed by a colon and one or more spaces, and then the value is stated. Having just one space after the colon is sufficient, but you can use more spaces for the sake of better readability if you like.
首先说明元素的键,然后说明冒号和一个或多个空格,然后说明值。 在冒号后面仅留一个空格就足够了,但是如果您愿意,可以使用更多的空格以提高可读性。
The equivalent PHP array of the above YAML is:
上述YAML的等效PHP数组是:
<?php array("id" => 2, "name" => "William O'Neil", "isActive" => false);And similar to enumerated arrays, you can express associative arrays on a single line using braces:
与枚举数组类似,您可以使用花括号在一行上表示关联数组:
{ id: 2, name: "William O'Neil”, isActive: false }With one or more spaces for indentation, you can represent a multi-dimensional array like so:
使用一个或多个缩进空间,您可以表示一个多维数组,如下所示:
author: 0: { id: 1, name: "Brad Taylor", isActive: true } 1: { id: 2, name: "William O'Neil", isActive: false }Note that although the second level arrays are enumerated arrays, I have used the syntax for mappings (colons) instead of the syntax for sequences (hyphens) for clarity.
请注意,尽管第二级数组是枚举数组,但是为了清楚起见,我使用了映射(冒号)语法而不是序列(连字符)语法。
The above YAML block is equivalent to the following PHP:
上面的YAML块等效于以下PHP:
<?php array( "author" => array( 0 => array("id" => 1, "name" => "Brad Taylor", "isActive" => true), 1 => array("id" => 2, "name" => "William O'Neil", "isActive" => false) ) );YAML also allows representing a collection of data elements in the same document without requiring a root node. The following example is the contents of article.yml which shows several multi-dimensional arrays in the same file.
YAML还允许在不需要根节点的情况下表示同一文档中数据元素的集合。 以下示例是article.yml的内容,该文件显示了同一文件中的多个多维数组。
author: 0: { id: 1, name: "Brad Taylor", isActive: true } 1: { id: 2, name: "William O'Neil", isActive: false } category: 0: { id: 1, name: "PHP" } 1: { id: 2, name: "YAML" } 2: { id: 3, name: "XML" } article: 0: id: 1 title: "How to Use YAML in Your Next PHP Project" content: > YAML is a less-verbose data serialization format. It stands for "YAML Ain't Markup Language". YAML has been a popular data serialization format among software developers mainly because it's human-readable. author: 1 status : 2 articleCategory: 0: { articleId: 1, categoryId: 1 } 1: { articleId: 1, categoryId: 2 }While most of YAML’s syntax is intuitive and easy to remember, there is one important rule to which you should pay attention. Indentation must be done with one or more spaces; tabs are not allowed. You can configure your IDE to insert spaces instead of tabs when you press tab key, which is a common configuration among software developers to make sure code is properly indented and displayed when it’s viewed in other editors.
尽管YAML的大多数语法都直观易记,但您应该注意一个重要规则。 缩进必须使用一个或多个空格进行; 标签是不允许的。 您可以将IDE配置为在按Tab键时插入空格而不是Tab,这是软件开发人员的常用配置,以确保代码正确缩进并在其他编辑器中查看时显示。
You can learn the more complex features and syntax that YAML supports by reading the official documentation, the Symfony reference, or Wikipedia.
通过阅读官方文档 , Symfony参考或Wikipedia ,可以了解YAML支持的更复杂的功能和语法。
If you’re researching YAML with your favorite search engine, you will undoubtedly find discussion on “YAML vs XML”, and naturally when you first experience YAML, you would tend to prefer it over XML mainly because its easier to read and write. However, YAML should be another tool in your developer arsenal and need not be an alternative to XML. Here are some advantages of YAML and XML.
如果您正在使用自己喜欢的搜索引擎来研究YAML,那么无疑会找到有关“ YAML vs XML”的讨论,自然地,当您第一次体验YAML时,您倾向于使用它而不是XML,主要是因为它易于读写。 但是,YAML应该是开发人员手中的另一个工具,并且不必替代XML。 这是YAML和XML的一些优点。
Advantages of YAML
YAML的优势
Less-verbose, easy to compose, and more readable 冗长,易于编写且可读性强 Need not have tree structure with a single parent node 不需要具有单个父节点的树结构Advantages of XML
XML的优点
More built-in PHP support compared to YAML 与YAML相比,更多的内置PHP支持 XML has been the de facto standard for inter-application communication and is widely recognized XML已成为应用程序间通信的事实上的标准,并得到了广泛认可 XML tags can have attributes providing more information about the enclosed data XML标签可以具有提供有关封闭数据的更多信息的属性Despite its verbosity, XML is more readable and maintainable when the hierarchy of elements is deep compared to YAML’s space-oriented hierarchy representation.
尽管其冗长,但与YAML的面向空间的层次结构表示相比,当元素的层次结构深入时,XML更具可读性和可维护性。
Considering the advantages of both languages, YAML seems to be more suitable for collections of different data sets and when humans are also among the data consumers.
考虑到两种语言的优势,YAML似乎更适合于收集不同的数据集,并且人类也属于数据使用者。
A YAML parser is expected to have two functionalities, some sort of load function that converts YAML into an array, and a dump function that converts an array into YAML.
YAML解析器应该具有两个功能,某种将YAML转换为数组的加载函数,以及将数组转换为YAML的转储函数。
Currently PHP’s YAML parser is available as a PECL extension and is not bundled with PHP. Alternatively, there are parsers written in pure PHP which would be slightly slower compared to the PECL extension.
当前,PHP的YAML解析器可作为PECL扩展使用,并且未与PHP捆绑在一起。 另外,也有一些用纯PHP编写的解析器,与PECL扩展相比,解析器会稍微慢一些。
The following are a few YAML parsers available for PHP:
以下是一些可用于PHP的YAML解析器:
PECL extension
PECL扩展
Is not bundled with PHP 未与PHP捆绑在一起 Will need root access to the server to install 将需要root访问服务器才能安装Symfony 1.4 YAML Component
Symfony 1.4 YAML组件
Implemented in PHP 用PHP实现 Will work in PHP 5.2.4+ 适用于PHP 5.2.4+ Need to extract from Symfony framework 需要从Symfony框架中提取Symfony 2 YAML Component
Symfony 2 YAML组件
Implemented in PHP 用PHP实现 Will work in PHP 5.3.2+ 适用于PHP 5.3.2+SPYC
间谍软件
Implemented in PHP 用PHP实现 Will work in PHP 5+ 适用于PHP 5+My preferred choice is the Symfony 1.4 YAML Component because of its portability (it works with PHP 5.2.4+ versions) and maturity (Symfony 1.4 is a well established PHP framework). Once you’ve extracted the YAML component from the Symfony archive, YAML classes are available under lib/yaml. The static methods load() and dump() are available with the sfYaml class.
我的首选是Symfony 1.4 YAML组件,因为它具有可移植性(适用于PHP 5.2.4+版本)和成熟度(Symfony 1.4是一个完善PHP框架)。 从Symfony存档中提取YAML组件后,可以在lib/yaml下使用YAML类。 sfYaml类提供了静态方法load()和dump() 。
Editor Note Oct 28 2012: The accompanying code on GitHub has been updated to use Composer for obtaining the PHPUnit and Symfony 1.4 YAML Component dependencies.
编者注:2012年10月28日: GitHub上的随附代码已更新,可以使用Composer获取PHPUnit和Symfony 1.4 YAML组件依赖关系。
Whenever you integrate a third-party class or library into your PHP project, it’s good practice to create a wrapper and a test suite. This let’s you later change the third party library with minimal changes to your project code (project code should only refer the wrapper) and with the assurance that change won’t brake any functionality (test suites will tell you).
每当您将第三方类或库集成到您PHP项目中时,创建包装器和测试套件都是一个好习惯。 这样一来,您便可以在以后对第三方库进行更改,而对项目代码的更改最少(项目代码应仅引用包装器),并确保更改不会破坏任何功能(测试套件会告诉您)。
Following is the test case (YamlParserTest.php) I created for my wrapper class (YamlParser.php). You need knowledge of PHPUnit to run and maintain the test case. You can add more tests if you’d like, for wrong file names and file extensions other than .yml, and other tests based on the scenarios you encounter in your project.
以下是测试案例( YamlParserTest.php )我对我的包装类(创建YamlParser.php )。 您需要PHPUnit的知识才能运行和维护测试用例。 如果需要,您可以添加更多测试,以用于错误的文件名和.yml以外的文件扩展名,以及基于项目中遇到的方案的其他测试。
<?php require_once "YamlParser.php"; class YamlParserTest extends PHPUnit_Framework_TestCase { private $yamlParser; public function setup() { $this->yamlParser = new YamlParser(); } public function testMainArrayKeys() { $parsedYaml = $this->yamlParser->load("article.yml"); $mainArrayKeys = array_keys($parsedYaml); $expectedKeys = array("author", "category", "article", "articleCategory"); $this->assertEquals($expectedKeys, $mainArrayKeys); } public function testSecondLevelElement() { $parsedYaml = $this->yamlParser->load("article.yml"); $actualArticle = $parsedYaml["article"][0]; $title = "How to Use YAML in Your Next PHP Project"; $content = "YAML is a less-verbose data serialization format. " . "It stands for "YAML Ain't Markup Language". " . "YAML has been a popular data serialization format among " . "software developers mainly because it's human-readable.n"; $expectedArticle = array("id" => 1, "title" => $title, "content" => $content, "author" => 1, "status" => 2); $this->assertEquals($expectedArticle, $actualArticle); } /** * @expectedException YamlParserException */ public function testExceptionForWrongSyntax() { $this->yamlParser->load("wrong-syntax.yml"); } }And here is the wrapper class:
这是包装器类:
<?php require_once "yaml/sfYaml.php"; class YamlParser { public function load($filePath) { try { return sfYaml::load($filePath); } catch (Exception $e) { throw new YamlParserException( $e->getMessage(), $e->getCode(), $e); } } public function dump($array) { try { return sfYaml::dump($array); } catch (Exception $e) { throw new YamlParserException( $e->getMessage(), $e->getCode(), $e); } } } class YamlParserException extends Exception { public function __construct($message = "", $code = 0, $previous = NULL) { if (version_compare(PHP_VERSION, "5.3.0") < 0) { parent::__construct($message, $code); } else { parent::__construct($message, $code, $previous); } } }So now you have the knowledge of what YAML is, how to represent PHP arrays in YAML, and how to integrate a PHP YAML parser into your projects. By spending little more time with YAML syntax, you will be able grasp the powerful features it offers. You may also consider exploring the Symfony 1.4 and 2 frameworks that use YAML extensively. And if you’re interested in playing with the code from this article, it’s available on GitHub.
现在,您已经了解了什么是YAML,如何在YAML中表示PHP数组以及如何将PHP YAML解析器集成到您的项目中。 通过花更多的时间使用YAML语法,您将能够掌握它提供的强大功能。 您也可以考虑探索广泛使用YAML的Symfony 1.4和2框架。 而且,如果您有兴趣使用本文中的代码 ,可以在GitHub上找到它。
Image via Fotolia
图片来自Fotolia
翻译自: https://www.sitepoint.com/using-yaml-in-php-projects/
相关资源:JAVA上百实例源码以及开源项目源代码