use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class MyClass { public function __construct(array $options) { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $options = $resolver->resolve($options); // rest of the constructor code... } private function configureOptions(OptionsResolverInterface $resolver) { $resolver->setRequired('foo') ->setAllowedTypes('foo', 'string') ->setDefault('bar', 'default_value') ->setAllowedTypes('bar', 'string') ->setNormalizer('foo', function(Options $options, $value) { return strtoupper($value); }); } } // Usage: $object = new MyClass(array( 'foo' => 'hello', // missing "bar" option will default to "default_value" )); // Output: echo $object->getFoo(); // HELLO echo $object->getBar(); // default_value
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class MyBaseClass { protected function configureOptions(OptionsResolverInterface $resolver) { $resolver->setDefined('baz') ->setAllowedTypes('baz', 'integer'); } } class MyClass extends MyBaseClass { public function __construct(array $options) { $resolver = new OptionsResolver(); $this->configureOptions($resolver); $options = $resolver->resolve($options); // rest of the constructor code... } protected function configureOptions(OptionsResolverInterface $resolver) { parent::configureOptions($resolver); $resolver->setRequired('foo') ->setAllowedTypes('foo', 'string') ->setDefault('bar', 'default_value') ->setAllowedTypes('bar', 'string'); } } // Usage: $object = new MyClass(array( 'foo' => 'hello', 'baz' => 123 )); // Output: echo $object->getFoo(); // hello echo $object->getBaz(); // 123 echo $object->getBar(); // default_valueThis example shows how to extend options from a base class using the OptionsResolverInterface. The MyBaseClass sets the rules for the "baz" option, while MyClass sets the rules for "foo" and "bar". The configureOptions() method is protected in both classes, but MyClass calls its parent's configureOptions() method first before setting its own rules. Package library: Symfony\Component\OptionsResolver