New in Symfony 2.6: Support for object-maps in YAML component
Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
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.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
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.
Maybe you could create an issue on the official Symfony repository to get feedback from the community?
As you suggested I will add a new issue to the Symfony repo later today.