Zend Framework: Coding by Convention
This is really something I've been wanting to point out because, for one, I very much like and agree with the approach, and second, it's something that any developer using the Zend Framework should digest and take into consideration when writing their own code.
There are numerous components that will accept configuration options, and usually that method is called setOptions($array) and it accepts an associative array (key/value pairs) as parameter.
And often, setOptions() iterates over the array and calls setOption($key, $value) as demonstrated by the following example:
public function setOptions($options)
{
foreach ($options as $option => $value) {
$this->setOption($option, $value);
}
return $this;
}
And typically, setOption() takes the first parameter (the key) and checks whether there's a method that matches "set" followed by the key name. For example, setOption('active', true) will end up calling setActive(true). The code often looks similar to the following:
public function setOption($option, $value)
{
$method = 'set' . $option;
if (is_method($this, $method)) {
$this->$method($value);
} else {
throw new Exception('Unknown option: ' . $option);
}
return $this;
}
This comes in handy when you're trying to configure a component that accepts a plethora of options, which you can then conveniently store in an array.
Furthermore, the constructor of a class could accept $options as first parameter (as is often the case), and also check whether it is an instance of Zend_Config, in which case it first converts it using $options = $options->toArray();
public function __construct($options = null)
{
if ($options instanceof Zend_Config) {
$options = $options->toArray();
}
if (is_array($options)) {
$this->setOptions($options);
}
}
Another convention you may have noticed is that the setter methods tend to "return $this;". This is known as fluent interface and allows for more concise, readable code by being able to chain method calls.
Posted: August 6th, 2009 under Development, PHP, Zend Framework.