YAML in PHP – fun with sfYaml

In a recent post about Symfony components – Fabien wrote about how the Symfony project (yes, that’s right – a capital S now!) will be releasing more and more components. In this post I introduce sfYaml, a YAML parser for PHP – building on my previous blog post about routing.

Our goal within this post is to convert a routing.yml configuration file into an collection of objects we could use to handle routing URLs to actions. First, we need to get a copy of the sfYaml code – we’ll get this from SVN.

Now we will create a very simple YAML file, which we will use to define routing rules. Our config file in the example will be identical to symfony’s routing.yml – so should be familiar with symfony users, but straight forward enough for people who aren’t familiar with symfony.

We will use sfYaml to read this file, and then create a sfPatternRouting object containing all our routes. First, let us see just how easy it is to read parse a YAML file:

The output:

Now we’ll build our sfPatternRouting object up, which is pretty much just a case of looping though this array:

This code is really simple, and to prove it works, we can test it as below:

Which shows the output you might expect:

sfYaml can do a little more than just this of course, and I suggest you look at the test code and the class source itself. As always, the best way to learn the features of code, is to actually read the source. This article should have given you a taste for just how easy it is, and got you up and running sufficiently to play with the classes yourself.

Note for symfony users: You might look at this example, and think that this is how symfony handles it’s routing – but actually, it’s not! symfony uses the sfRoutingConfigHandler class, which handles generating PHP code from the YAML, which is written out into the cache folder. This means that the YAML file is not parsed on each request. Below is the code that symfony 1.2 (yes, lower case ‘s’ for symfony 1.2! 😉 ) generates from our routing.yml – just so you can see how it does it. After this code is generated, it can simply be included:

1 thought on “YAML in PHP – fun with sfYaml”

  1. Thanks, your post is interesting 🙂

    Till now I’m using sfYaml just to create and manage easy config files, and adapted to them a class of mine to dialogue with mysql db. I’m thinkin’ on new uses like you did.


Leave a Reply

Your email address will not be published. Required fields are marked *