RockyFord
RockyFord

Reputation: 8519

Zend Framework Quickstart Model constructor

using the ZF quickstart create model, as a basis for this topic.
I would like to understand exactly what the __construct and the setOptions() method are supposed to be doing in this context.
No matter how many times I bang on it, I'm just no getting what these two methods are doing.

 public function __construct(array $options = null)
    {
        //if it is an array of options the call setOptions and apply those options
        //so what? What Options
        if (is_array($options)) {
            $this->setOptions($options);
        }
    }

 public function setOptions(array $options)
    {
       //I can see this starts by getting all the class methods and return array()
        $methods = get_class_methods($this);
       //loop through the options and assign them to $method as setters?
        foreach ($options as $key => $value) {
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }

I really get lost on the setOptons(), I can't figure out what it's trying to accomplish. I understand it's abstracting some behavior, I just can't quite fathom what.
So far as I can tell, this is just so much 'so what!'. I would like to understand it as it might prove important.

Upvotes: 4

Views: 619

Answers (1)

Raj
Raj

Reputation: 22926

If you pass $options as array

 { ["name"] => "RockyFord" }

then setOptions method will call

setName("RockyFord");

if setName method exists in this class.

    foreach ($options as $key => $value) { // Loops through all options with Key,Value
        $method = 'set' . ucfirst($key); // $method becomes 'setName' if key is 'name'
        if (in_array($method, $methods)) { // Check if this method (setName) exists in this class
            $this->$method($value); // Calls the method with the argument
        }
    }

Upvotes: 4

Related Questions