The OptionsResolver component helps you configure objects with option arrays. In Symfony 5.1 we've improved it with the following features.
Contributed by
Lorenzo Millucci
in #33848.
It's common to configure several features for each option (its allowed types,
its default values, whether it's required or not, etc.) Thanks to the new
define()
method, you can use a fluent interface to configure everything
about an option without repeating its name in different methods:
1 2 3 4 5 6 7 8 9 10 | // Before
$resolver->setRequired('host');
$resolver->setDefaults(['host' => 'smtp.example.org']);
$resolver->setAllowedTypes('host', 'string');
// After
$resolver->define('host')
->required()
->default('smtp.example.org')
->allowedTypes('string');
|
Contributed by
Yonel Ceruto
in #35400.
Sometimes, the name of an option or its highly dynamic feature makes it hard to understand the error messages generated by Symfony. That's why in Symfony 5.1 we've introduced a new method which improves DX (developer experience) allowing you to add a description/help/debug message for the option.
Imagine that you define a datetime option whose value must be in the future:
1 2 3 | $resolver->setAllowedValues('scheduledAt', static function ($value): bool {
return $value >= new \DateTime('now');
});
|
This is the standard error message displayed by Symfony in this case:
1 | The option "scheduledAt" with value DateTime is invalid.
|
However, if you add the info()
or setInfo()
methods:
1 2 3 4 5 6 7 | // using the traditional syntax
$resolver->setInfo('scheduledAt', 'It must be a date in the future.');
// using the fluent interface
$resolver->define('scheduledAt')
// ...
->info('It must be a date in the future.');
|
The error message displayed now is:
1 2 | The option "scheduledAt" with value DateTime is invalid.
Info: It must be a date in the future.
|
What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...