New in Symfony 5.1: OptionsResolver improvements

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

The OptionsResolver component helps you configure objects with option arrays. In Symfony 5.1 we've improved it with the following features.

Fluent Interface

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');

Option Debug Information

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.
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

Fluent!!! ❤️ Finally!! ❤️
Very nice !
it's great!

Comments are closed.

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