It seems obvious that almost every application has its configuration. We can use a lot of data formats for configuration files, for example YAML or XML, JSON or plain PHP (replace with any language you use) files. Personally I like and prefer to use YAML to other formats and here I just want to describe a little one of Symfony components called YAML. Also It's quite interesting for me which format you use, what pros and cons you see, so don't hesitate to leave a comment with your thoughts.
Accordingly to its documentation, YAML is a human friendly data serialization standard for all programming languages. PHP doesn't support YAML out of the box and that's why you have a few choices:
- install PECL extension for YAML
- use any PHP implementation that you like
Variant with PECL extension seems bad for me, because sometimes you just don't have all needed rights to install extensions on your client's hosting. That's why I prefer to use PHP implementations.
Symfony framework is based on top of a lot of useful components which you can separately use in your projects. One of such useful components is YAML component. Let's go through it to check how it works and then discuss pros and cons of YAML format in general.
As always, installation with composer is straightforward:
composer require symfony/yaml
This will add YAML component to your composer.json file and you will get all needed classes to work/support YAML in your project.
Let's assume that we have a configuration file:
# config.yml db: user: victor pass: ~ name: 4devs host: localhost port: ~ map: api_key: 12345
Now we can process this configuration with Yaml class:
<?php // parser.php require __DIR__ . '/../vendor/autoload.php'; use Symfony\Component\Yaml\Yaml; $config = Yaml::parse(file_get_contents('config.yml')); print_r($config);
Array ( [db] => Array ( [user] => victor [pass] => [name] => 4devs [host] => localhost [port] => ) [map] => Array ( [api_key] => 12345 ) )
That's it. Simple enough? Even if It does not support the whole YAML specification it still supports most useful data types, like strings, integers, boolean values, arrays, hashes and so on. You can always go further and read official documentation for this component on symfony site.
+ we don't need to install additional PHP extensions
+ easy to understand this format
+ configuration takes really less time and space comparing to XML
+ can be used for any language and be a bridge between programms written in different languages
- doesn't have deep integration with IDE and syntax validation (you will get an exception only in runtime)
- one more standard to learn?
With a few lines of code we're able to add YAML format configuration support to our application. I know that YAML is not the best solution ever, and there exist places and time for it and that's why I have a few questions:
- what data format do you prefer to use in your projects and why?
- any suggestions for other YAML libraries?