如何在没有样板的PHP中构建知道继承链的静态属性

时间:2015-04-02 17:02:34

标签: php oop inheritance

我一直在努力在PHP中实现OOP概念,而解决方案正在逃避我。我有一个抽象基类,其构造函数基于参数数据的关联数组在调度表中调用一系列setter,如下所示:

abstract class Base {
    protected static $_SETTER_DISPATCH_MODEL = array();

    public function __construct(array $data) {
        foreach (static::$_SETTER_DISPATCH_MODEL as $dataKey => $method) {
            if (array_key_exists($dataKey, $data)) {
                if (method_exists($this, $method)) {
                    $this->$method($data[$dataKey]);
                }
                else {
                    // Handle error
                }
            }
        }
    }
}

我想要做的是能够在我的基类中定义一个方法,通过将子类的dispatch表与每个父类的dispatch表合并来构建setter dispatch表,所以我可以这样做:

class Foo extends Base {
    protected static $_SETTER_DISPATCH_MODEL = array('foo' => 'setFoo');
}

class Bar extends Foo {
    protected static $_SETTER_DISPATCH_MODEL = array('bar' => 'setBar');
    // The base constructor should call setFoo() and setBar()
}

class Baz extends Bar {
    protected static $_SETTER_DISPATCH_MODEL = array('baz' => 'setBaz');
    // The base constructor should call setFoo(), setBar(), and setBaz()
}

我无法找到在基类中定义此行为的方法,并使其考虑到继承链中一直发生的所有事情。我能够做出我正在尝试做的唯一方法是创建第二个属性,其中包含类希望添加到模型的setter,并将此样板构造函数添加到每个子类:< / p>

public function __construct(array $data) {
    if (!array_key_exists(
        key(self::$_SUPPLEMENTAL_SETTER_DISPATCH_MODEL),
        static::$_SETTER_DISPATCH_MODEL
    )) {
        static::$_SETTER_DISPATCH_MODEL = array_merge(
            static::$_SETTER_DISPATCH_MODEL,
            self::$_SUPPLEMENTAL_SETTER_DISPATCH_MODEL
        );
    }
    parent::__construct($data);
}

必须有更好的方法来做到这一点,对吧?

0 个答案:

没有答案