Skip to content

Instantly share code, notes, and snippets.

@webmozart
Created February 2, 2011 15:10
Show Gist options
  • Select an option

  • Save webmozart/807810 to your computer and use it in GitHub Desktop.

Select an option

Save webmozart/807810 to your computer and use it in GitHub Desktop.
Using a static Options class with utility functions
+ Type hints (because setters are called)
+ Options are set in the very beginning of the constructor
+ Good performance
+ Everything is a property, no special treatment of options
- Verbose
- No error if unsupported options are given
<?php
class Thing
{
protected $required;
public function __construct(array $options = array())
{
$this->setRequired(Options::get($options, 'required', true)); // or
$this->required = Options::get($options, 'required', true);
}
}
// WHAT'S REALLY UGLY: Lots of options are very verbose
class OtherThing
{
private $widget;
private $type;
private $pattern;
private $years;
private $months;
private $days;
private $format;
private $dataTimezone;
private $userTimezone;
public function __construct(array $options = array())
{
$this->widget = Options::get($options, 'widget', self::CHOICE);
$this->type = Options::get($options, 'type', self::DATETIME);
$this->pattern = Options::get($options, 'pattern');
$this->years = Options::get($options, 'years', range(date('Y') - 5, date('Y') + 5));
$this->months = Options::get($options, 'months', range(1, 12));
$this->days = Options::get($options, 'days', range(1, 31));
$this->format = Options::get($options, 'format', self::MEDIUM);
$this->dataTimezone = Options::get($options, 'data_timezone', 'UTC');
$this->userTimezone = Options::get($options, 'user_timezone', 'UTC');
}
}
// WHAT'S SOMEWHAT UGLY: Option typos
$thing = new OtherThing(array('datatimezone' => 'Europe/Paris'));
// won't complain, but data_timezone is still "UTC"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment