1 OptionsResolver Component
2 =========================
4 OptionsResolver helps at configuring objects with option arrays.
6 It supports default values on different levels of your class hierarchy,
7 option constraints (required vs. optional, allowed values) and lazy options
8 whose default value depends on the value of another option.
10 The following example demonstrates a Person class with two required options
11 "firstName" and "lastName" and two optional options "age" and "gender", where
12 the default value of "gender" is derived from the passed first name, if
13 possible, and may only be one of "male" and "female".
15 use Symfony\Component\OptionsResolver\OptionsResolver;
16 use Symfony\Component\OptionsResolver\OptionsResolverInterface;
17 use Symfony\Component\OptionsResolver\Options;
23 public function __construct(array $options = array())
25 $resolver = new OptionsResolver();
26 $this->setDefaultOptions($resolver);
28 $this->options = $resolver->resolve($options);
31 protected function setDefaultOptions(OptionsResolverInterface $resolver)
33 $resolver->setRequired(array(
38 $resolver->setDefaults(array(
40 'gender' => function (Options $options) {
41 if (self::isKnownMaleName($options['firstName'])) {
49 $resolver->setAllowedValues(array(
50 'gender' => array('male', 'female'),
55 We can now easily instantiate a Person object:
57 // 'gender' is implicitly set to 'female'
58 $person = new Person(array(
59 'firstName' => 'Jane',
63 We can also override the default values of the optional options:
65 $person = new Person(array(
66 'firstName' => 'Abdullah',
67 'lastName' => 'Mogashi',
72 Options can be added or changed in subclasses by overriding the `setDefaultOptions`
75 use Symfony\Component\OptionsResolver\OptionsResolver;
76 use Symfony\Component\OptionsResolver\Options;
78 class Employee extends Person
80 protected function setDefaultOptions(OptionsResolverInterface $resolver)
82 parent::setDefaultOptions($resolver);
84 $resolver->setRequired(array(
88 $resolver->setDefaults(array(
89 // $previousValue contains the default value configured in the
91 'age' => function (Options $options, $previousValue) {
92 return self::calculateAge($options['birthDate']);
103 You can run the unit tests with the following command:
105 $ cd path/to/Symfony/Component/OptionsResolver/
106 $ composer.phar install --dev