是否有可用于消除约定样板代码的基本Zend类?

时间:2011-12-21 21:20:10

标签: zend-framework

我在Zend Framework类中注意到的一种模式是非常类似于以下的代码。它可以在大约20-30个文件中。

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;
}

当我开发自己的课程时,我也会输入类似的锅炉板代码。是否有一个Zend Framework类已经有了我可以扩展的最小锅炉板代码?

如果没有,为什么不存在?保持代码DRY并保持一致会不会有帮助吗?

1 个答案:

答案 0 :(得分:2)

我不是ZF的贡献者,但我相信答案很简单,随着时间的推移,随着组件被添加到框架中,这已经发展成为一种约定。 ZF2(目前处于测试阶段)使用其他组件可以扩展的标准Options类来解决这个问题 - 请参阅https://github.com/zendframework/zf2/blob/4f3c989efd04f07c78415192b0dee3c867e02199/library/Zend/Stdlib/Options.php

在短期内,如果你发现自己需要类似的东西,为什么不创建这样的类,你自己的类可以扩展。

相关问题