April 27, 2016 Javier Eguiluz

YAML is one of the most popular formats to define the configuration of Symfony applications. Besides, the YAML Component is our second most popular component, with tens of millions of downloads and thousands of PHP projects depending on it.

In previous Symfony versions, the behavior of the parse() and dump() methods were partially configurable. For example, the parse() method defined a boolean argument to configure the behavior of object maps and you could also toggle object support with the fifth parameter of the dump() method:

1 2 3 use Symfony\Component\Yaml\Yaml ; Yaml :: dump ( array ( 'foo' => new A (), 'bar' => 1 ), 0 , 4 , false , true );

However, these features had some drawbacks. First, boolean arguments (also called "flag arguments") are usually not recommended. Second, this doesn't scale well because it forces you to define new method arguments for the new features.

Introducing configuration flags¶ In Symfony 3.1, to avoid all the issues mentioned above and to keep adding new features, we decided to introduce configuration flags for the YAML component. These flags are constants defined in the Symfony\Component\Yaml\Yaml class. For example, to enable the object support for the dump() method, use the Yaml::DUMP_OBJECT constant: 1 2 3 use Symfony\Component\Yaml\Yaml ; Yaml :: dump ( array ( 'foo' => new A (), 'bar' => 1 ), 0 , 4 , Yaml :: DUMP_OBJECT ); Thanks to this flag-based configuration mechanism, we've started adding lots of new features to the YAML component. Keep reading to learn about some of those features.

Showing exceptions on invalid types¶ The new Yaml::DUMP_EXCEPTION_ON_INVALID_TYPE flag replaces the fourth argument of the dump() method and it makes the application to trigger exceptions when an invalid type is passed (for example when dumping PHP resources): 1 Yaml :: dump ( array ( 'foo' => new A (), 'bar' => 1 ), 0 , 4 , Yaml :: DUMP_EXCEPTION_ON_INVALID_TYPE );

Dumping objects as maps¶ Consider the following PHP object: 1 2 3 $object = new \stdClass (); $object -> foo = 'foo' ; $object -> bar = new \StdClass (); The regular dump() method won't provide the results you may expect, but the new Yaml::DUMP_OBJECT_AS_MAP flag will dump the object as expected: 1 2 3 4 5 $dumpedObject = Yaml :: dump ( $object , 0 , 4 ); // $dumpedObject = "{ object: null }" Yaml :: dump ( $object , 0 , 4 , Yaml :: DUMP_OBJECT_AS_MAP ); // $dumpedObject = "{ object: { foo: foo, bar: { } } }"