Created
February 2, 2011 15:15
-
-
Save webmozart/807818 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Using a static OptionSupport class that automatically writes options into properties | |
+ Options are set in the very beginning of the constructor | |
+ Concise | |
+ Error if option is not supported | |
+ Everything is a property, no special treatment of options | |
~ Medium performance. Reflection is slow, but some things can be cached so it is faster than addOption() | |
- Options need to be converted to camel case | |
- Problems with accessing required options before parent::__construct() | |
<?php | |
class Thing | |
{ | |
public static $options = array('required'); | |
public static $requiredOptions = array('required'); | |
protected $required = false; // default value is false | |
public function __construct(array $options = array()) | |
{ | |
OptionSupport::initialize($this, $options); | |
} | |
} | |
// WHAT'S REALLY UGLY: Accessing options before parent::__construct() | |
class OtherThing extends Thing | |
{ | |
public static $options = array('newoption'); | |
public static $requiredOptions = array('newoption'); | |
protected $newoption; | |
// this could even be in the parent class so that you don't even know | |
// that doSomethingBeforeParentConstruct() is called before the root constructor | |
public function __construct(array $options = array()) | |
{ | |
$this->doSomethingBeforeParentConstruct(); | |
parent::__construct($options); | |
} | |
public function doSomethingBeforeParentConstruct() | |
{ | |
// newoption is an required option, so we assume it is there | |
$this->newoption->doSomething(); // BOOM! newoption is NULL | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment