The Configuration Pattern in Zend Framework

Several components in Zend Framework such as Zend_Form and Zend_Layout, support what I’ve come to call the Configuration Pattern. Though it doesn’t appear to exist in any officially sanctioned capacity like traditional design patterns, and it may qualify more as a convention than a design pattern, it seems to me that it’s something worth knowing about.

Here’s how it works. Have a look at the constructor for Zend_Form. It accepts an $options parameter, which can be an associative array or Zend_Config instance. If it’s an array, setOptions() is called. If it’s a Zend_Config instance, setConfig() is called, which then converts the Zend_Config instance to an associative array and passes that to setOptions(). So, either way, you end up in the same method with the same type of data.

setOptions() then iterates over the associative array it receives. It takes the index of each element and looks for a corresponding setter method. For example, if the array contains an element with the index ‘viewScriptPath’, setOptions() would check the class definition for a method setViewScriptPath() using method_exists(). Since that method does exist in Zend_Form, it would be called and passed the value from the associative array corresponding to that index.

This alleviates the need to explicitly call a setter method for every value you want to set. While that approach is slightly more efficient — not using setOptions() means one less function call and no method_exists() calls, which are slightly expensive — it can make code using the class in question look overly verbose or cluttered.

Alternatively, the setOptions() method could be called after the class was instantiated. With respect to that approach, passing an array or Zend_Config instance to the constructor only saves you one line of code on the calling end.

To get a list of classes that use this pattern, you can issue the bash command shown below from the library directory of your Zend Framework installation.

grep "\$this->setOptions" * | sort | uniq

One Comment

  1. Hello colleague blogger,
    the "unified constructor" or "Configuration pattern" has been confirmed as a current guideline for Zend Framework components by Matthew Weier O’Phinney:
    http://giorgiosironi.blogspot.com/2009/09/zend-framework-api-what-options-is.html