Yaml and PHP: Simple yet powerful

Mike Wenger
4 min readJul 7, 2017

--

As a designer turned front-end developer, I greatly appreciate efficiency and readability in code. Just in the same way good design lends to better readability and a stronger interaction with the reader, a well-organized and easily readable code structure is key to readability and to a headache-free environment. I’ll say that Base64 encryption and serialization are a great way to compress non-sensitive data — until you reverse the process. Good luck reading that.

Enter YAML: a concise, human-readable and lightweight solution to oh-so many common coding problems.

YAML was born in part out of a frustration with XML syntax and how difficult it can be to read — with all of its tags and seemingly extraneous markup. It was conceived as a way to create something that made more sense.

It’s now beginning to gain ground and popularity with a wide variety of uses, particularly with Content Management Systems (CMSs). It’s used in one of my favorite CMSs, Statamic.

Statamic uses YAML in conjunction with markdown as the entire basis for saving and serving content instead of a database. The lightweight and file-based nature of YAML makes it ideal for simple backups and allows for full version control — if you’re not using a database with it. Another great thing about YAML is that it’s flexible and extensible, just like XML.

The YAML syntax

While YAML has many uses with other languages, I’ll focus on the interaction between YAML and PHP specifically, due to similarities they share. YAML syntax follows a close resemblance to a PHP array — and when used in conjunction with a parser, like Symfony, it can be put into a PHP array with ease.

The following PHP associative arrays would be the equivalent to the following YAML:

PHP: 
Array(
[0] => ‘value’
[1] => ‘second value’
)
Array(
‘key’ => ‘value’
’key’ => Array(
‘key’ => ‘sub value’
‘key’ => ‘another value’
)
)
YAML:
- ‘value’
- ‘second value’
key: ‘value’
key:
key: ‘sub value’
key: ‘another value’

Because I began using YAML in Statamic, which uses the above method for handling sub arrays, and because I like straightforward readability, I opt for sub-arrays to be on their own line. However, you can use inline formatting for both enumerated and associative arrays in YAML. Enumerated arrays are formatted with square brackets ([‘value’,’second value’]), while associative arrays are formulated with curly braces ({key: ‘sub value’, key: ‘another value’}).

It is very important to understand that sub array delineation in YAML must be done with spaces, not indentions. The number of spaces must be equal between each level as well, so if you use 4 spaces to indent a subarray you will need to use eight spaces to delineate a sub-subarray — or else you will be served with errors!

If you’re ready to work with YAML in PHP, you’ll need a little configuration, as PHP cannot natively handle YAML data. Rest easy though; the Symfony library YAML component makes it a breeze.

Working with the Symfony component

Symfony is an amazing PHP development framework that allows you to now pull out components to be used on their own and is great to use with Statamic. The YAML component can do everything you need with a 106k footprint. Fire up the classes with SplClassLoader and start writing PHP to parse and dump YAML for whatever you can imagine doing with it.

The method I just mentioned would look like this:

<?php 
require_once '/path_to_file/SplClassLoader.php';
$loader = new SplClassLoader(
'Symfony',
'/path_to_symfony_directory/'
);
$loader->register();
?>

‘Symfony’ in the example above would be the name of the Symfony directory holding the YAML component, while the path would include the path to the directory above, and not include the path to ‘Symfony.’

After the classes are loaded, we can then use the following:

<?php 
use Symfony\Component\YAML\YAML;
function parse_YAML($file=false)
{
$YAML = YAML::parse($file);
return $YAML;
}
function dump_YAML($array=false,$file=false)
{
if (is_array($array))
{
$YAML = YAML::dump($array,6,4);
file_put_contents($file, $YAML);
}
}
?>

The above functions will get you going with reading and writing to and from a YAML file. You can easily extend or modify the functions to work directly with YAML and bypass the file if you like.

In the above example, I’ve specified the ‘switch to inline YAML’ in YAML::dump to be set at six. For my purposes, this will always dump the YAML to use indentions and not switch to inline format. The next parameter in the dump function is how many spaces to use in each new line — I personally like four for the sake of readability.

What can YAML be used for?

YAML is widely used in conjunction with PHP for configuration files that are easily readable and quick to load to a PHP array. As I already mentioned, Statamic uses it for storing and loading data as text/content. It can also be used as a log method, since YAML is easy to read.

I used it recently as a cache method — it made debugging a breeze and saves in a lightweight format. If you look at the inline format of YAML, I think it closely resembles JSON format as well, which I’ve also used as a cache method.

Due to its flexibility, I feel the uses for YAML will only grow and get more creative and interesting.

--

--

Mike Wenger

I’m a web-minded user experience designer and front-end developer with a passion for creating engaging and effective products.