4

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.

1 Answer 1

4

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
        }
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I understand all of a sudden. This allows us to pass an array instead explicitly calling get* or set*

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.