New in Symfony 2.6: Support for object-maps in YAML component

Contributed by
Zachary Tong and Nicolas Grekas
in #10552.

YAML Component adds support for parsing and dumping YAML formatted files in PHP applications. Although it doesn't implement the full YAML 1.2 specification yet, it supports most of its features.

Symfony 2.6 will introduce support for a new YAML feature: object maps. In previous versions, the parser returned associative PHP arrays for maps ({ 'key1': 'value1', 'key2': 'value2' }). This could cause some troubles when YAML is serialized into other formats such as JSON. Now, when the user enables object-map support, maps are represented by stdClass() objects instead of regular arrays.

In order to enable the support for object maps, you must pass the true value to the new fourth argument of the parse() method. Its default value is false to maintain backwards compatibility. Here are some examples of the new parse() method behavior:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
use Symfony\Component\Yaml\Parser;
$yaml = new Parser();

$yaml->parse('[  foo, [  bar, foo  ]  ]', false, false, true);
// output: array('foo', array('bar', 'foo'))

$yaml->parse('[ { foo: { bar: foo } } ]', false, false, true);
// output: array((object) array('foo' => (object) array('bar' => 'foo')))

$yaml->parse('{ foo: bar, bar: { } }', false, false, true);
// output: (object) array('foo' => 'bar', 'bar' => new \stdClass())

$yaml->parse('{ foo: bar, bar: { } }', false, false, false);
// output: (object) array('foo' => 'bar', 'bar' => array())

$yaml->parse('{ foo: [ ], bar: { } }', false, false, true);
// output: (object) array('foo' => array(), 'bar' => new \stdClass())

$yaml->parse('{ foo: [ ], bar: { } }', false, false, false);
// output: (object) array('foo' => array(), 'bar' => array())

This new feature was introduced by Zachary Tong and Nicolas Grekas in the PR #10552.

Comments

Great feature!!!
Hello, Javier!

Great feature to have indeed, but I was wondering if it would not have been better to return by default an object that implemented the ArrayAccess interface for backwards compatibility and drop the other parameter altogether?
That way we can have returned a custom object implementing a custom interface than a simple stdClass. A see a lot more possibilities with this scenario, do you agree?

Thanks.
@Denis, to be completely honest, I see your approach much more complete but I don't really know if returning StdClass is a "good enough solution".

Maybe you could create an issue on the official Symfony repository to get feedback from the community?
Thank you for the feedback, Javier!
As you suggested I will add a new issue to the Symfony repo later today.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.