New in Symfony 3.2: PHP constants in YAML files
Contributed by
Jules Pietri
in #18626.
YAML is arguably the most popular format to define the configuration of the Symfony applications. Unfortunately, due to the YAML format nature, it doesn't provide feature parity with other formats such as XML. In particular, it's not possible to use PHP constants in YAML files, for example as service arguments.
In Symfony 3.2, we decided to augment the YAML format with a custom
extension to support PHP constants. If some content in a YAML file is
prefixed with the !php/const:
string, it's now considered a PHP constant:
1 2 3 4 5 6 7 | parameters:
# this is considered a regular string
foo: PHP_INT_MAX
# this is considered a PHP constant
bar: !php/const:PHP_INT_MAX
# starting from Symfony 3.4, use this syntax instead:
bar: !php/const PHP_INT_MAX
|
By default, the Symfony Yaml component only parses/generates standard-
compliant YAML contents. Therefore, when using the stand-alone Yaml component,
you must enable this feature explicitly with the Yaml::PARSE_CONSTANT
flag:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | use Symfony\Component\Yaml\Yaml;
$yaml = <<<YAML
foo:
!php/const:PHP_INT_MAX
YAML;
// starting from Symfony 3.4, use this syntax instead:
$yaml = <<<YAML
foo:
!php/const PHP_INT_MAX
YAML;
$config = Yaml::parse($yaml, Yaml::PARSE_CONSTANT);
// $config = array('foo' => PHP_INT_MAX);
|
If you use the Symfony framework, this option is enabled by default in the YamlFileLoader used by the DependencyInjection component. This means that you can use PHP constants in your YAML services out-of-the-box:
1 2 3 4 5 6 7 8 9 10 11 | # app/config/services.yml
services:
app.my_service:
# ...
arguments:
- '@app.other_service'
- !php/const:AppBundle\Entity\BlogPost::MUM_ITEMS
- !php/const:Symfony\Component\HttpKernel\Kernel::VERSION
# starting from Symfony 3.4, use this syntax instead:
- !php/const AppBundle\Entity\BlogPost::MUM_ITEMS
- !php/const Symfony\Component\HttpKernel\Kernel::VERSION
|
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.
New in Symfony 3.2: PHP constants in YAML files symfony.com/blog/new-in-symfony-3-2-php-constants-in-yaml-files
Tweet thisComments
services:
app.my_service:
# ...
arguments:
- '@app.other_service'
- ENV_VAR
Where ENV_VAR is an env variable defined on user session scope.
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
Khaled ADALA said on Jun 30, 2016 at 07:57 #1