One of the things I've really liked about writing MooTools classes is
the syntax. After spending about a solid month working exclusively on
MooTools classes, when I went back to some PHP, I found I really
missed the options syntax for the class constructor, so I decided to
try to implement Moo-style options for PHP classes. This isn't really
anything special, but since it's inspired by MooTools, I thought I
would share because someone might find it interesting.

The options class:

<?php
class VMClass {

        // @var array $options - The generic options array for which
extending classes should set default values
        public $options = array();

        /**
        * Description: The setOptions method should be called in the
constructor of an extending class
        * @param array $options - The options array resets any default
options present in the class
        * @return - $this
        */
        protected function setOptions($options) {
                if (is_array($options)){
                        foreach ($options as $key => $value){
                                $this->options[$key] = $value;
                        }
                        $this->options = $this->arrayToObject($this->options);
                }
                return $this;
        }

        /**
        * Description: Recursively returns an array as an object, for easier
syntax
        * Credit: Mithras @ 
http://us2.php.net/manual/en/language.types.object.php#85237
        * @param array $array - The array to return as an object
        * @return - The object converted from the array
        */
        public function arrayToObject(array $array){
                foreach ($array as $key => $value){
                if (is_array($value)) $array[$key] = $this-
>arrayToObject($value);
                }
                return (object) $array;
        }
}
?>

A silly test class that extends the above class:

<?php
class TestClass extends VMClass {

        public $options = array(
                'name'          => array('first'=>'Fred',
                                                        'last'=>'Flintstone'),
                'question'      =>'How are you?',
                'useQuestion' => TRUE
        );

        function __construct($options = null){
                $this->setOptions($options);
        }

        public function greet($salutation){
                echo $salutation.', '.$this->options->name->first.' 
'.$this->options-
>name->last.'. ';
                if ($this->options->useQuestion) echo $this->options->question;
        }
}
?>

And finally, a simple test case of our test class:

<?php
include('vmclass.php');
include('testclass.php');
$options = array('question'=>'Que pasa?', 'useQuestion'=>TRUE);
$foo = new TestClass($options);
$foo->greet('Howdy');
$foo->options->name->first = 'Wilma';
$foo->options->useQuestion = FALSE;
$foo->greet('Bonjour');
?>

Reply via email to