Richard Ayotte
Richard Ayotte

Reputation: 5080

Is there a base Zend class that can be used to eliminate conventions boilerplate code?

One of the patterns that I've noticed in the Zend Framework classes is code very similar to the following. It can been in some 20-30 files.

public function __construct($options = null)
{
    if (is_array($options)) {
        $this->setOptions($options);
    } elseif ($options instanceof Zend_Config) {
        $this->setConfig($options);
    }

    // do custom initialization
    $this->_init();
}

public function setOptions(array $options)
{
    foreach ($options as $key => $value) {
        $this->set($key, $value);
    }

    return $this;
}

public function set($property, $value)
{
    if (!is_string($property) || empty($property)) {
        require_once 'Zend/Navigation/Exception.php';
        throw new Exception('Invalid argument: $property must be a non-empty string');
    }

    $method = 'set' . self::_normalizePropertyName($property);

    if ($method != 'setOptions' && $method != 'setConfig' &&
        method_exists($this, $method)) {
        $this->$method($value);
    } else {
        $this->_properties[$property] = $value;
    }

    return $this;
}

When I develop my own classes, I also put in similar boiler plate code. Is there a Zend Framework class that already has this minimal boiler plate code that I could extend instead?

If not, why isn't there one? Would it not help to keep the code DRY and consistent?

Upvotes: 1

Views: 112

Answers (1)

Tim Fountain
Tim Fountain

Reputation: 33148

I'm not a ZF contributor but I believe the answer is simply that this has evolved over time into a convention as components have been added to the framework. ZF2 (currently in beta) does address this with a standard Options class that other components can extend - see https://github.com/zendframework/zf2/blob/4f3c989efd04f07c78415192b0dee3c867e02199/library/Zend/Stdlib/Options.php

In the short term, if you find yourself needing something similar why not create a class like this that your own classes can extend.

Upvotes: 2

Related Questions