Advertisement
Guest User

Untitled

a guest
Nov 8th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. /**
  4.  * The static members defined in this class, pertaining
  5.  * to the options, are required by several classes to
  6.  * manage default, static, and instance configuration
  7.  * options, each overriding the last respectively.
  8.  *
  9.  * The instance method is just an example.
  10.  */
  11. class Options{
  12.  
  13.     private $_options = array();
  14.     private $_options_defaults = array(
  15.         'flag_foo' => true,
  16.         'flag_bar' => true,
  17.     );
  18.    
  19.     public function setOption($name, $value){
  20.         static::$_options[$name] = $value;
  21.     }
  22.    
  23.     public function setOptions(Array $options, $merge = true){
  24.         if($merge){
  25.             static::$_options = array_replace(static::$_options, $options);
  26.         }else{
  27.             static::$_options = $options;
  28.         }
  29.     }
  30.    
  31.     public function getOption($name){
  32.         if(isset(static::$_options[$name])){
  33.             return static::$_options[$name];
  34.         }
  35.         if(isset(static::$_options_defaults[$name])){
  36.             return static::$_options_defaults[$name];
  37.         }
  38.         return null;
  39.     }
  40.    
  41.     public function getOptions(){
  42.         return array_replace(static::$_options_defaults, static::$_options);
  43.     }
  44.    
  45.     public function useCaseOfClassWithOptions(Array $options = array()){
  46.         $options = array_replace(static::getOptions(), $options);
  47.         if(true === $options['flag_foo']){
  48.             // do the foo
  49.         }
  50.         if(true === $options['flag_bar']){
  51.             // do the bar
  52.         }
  53.     }
  54. }
  55.  
  56. class ClassThatNeedsOptions {
  57.    
  58.     private $options;
  59.    
  60.     public function __construct(Options $options) {
  61.         $this->options = $options;
  62.     }
  63.    
  64.     public function useCaseOfClassWithOptions(Array $options){
  65.         $options = array_replace($this->options->getOptions(), $options);
  66.         if(true === $options['flag_foo']){
  67.             // do the foo
  68.         }
  69.         if(true === $options['flag_bar']){
  70.             // do the bar
  71.         }
  72.     }
  73. }
  74.  
  75. new ClassThatNeedsOptions(new Options);
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement