How to Extend a Fieldset in ZF2

2019-08-31 04:20发布

问题:

Doctrine’s Class Table Inheritance mapping strategy involves joining a parent table with one of a number of child tables depending on the value in a discriminator column in the parent table. For example, a parent table might contain the columns a, b, and c; with the values in column c being either foo or bar. A child table named ‘foo’ might contain the columns d, e, f and g; while a child table named ‘bar’ might contain the columns p, q, r and s. A single entity is defined for the parent and a separate entity is defined for each child (‘foo’ and ‘bar’). In the inheritance mapping strategy, the child entities ‘extend’ the parent entity, so there is no need in the child to redefine elements in the parent.

My question is, can we ‘extend’ the child fieldsets as well? The ‘foo’ fieldset is going to consist of elements a, b, c, d, e, f and g and the ‘bar’ fieldset is going to consist of elements a, b, c, p, q, r and s. Do we really need to define the options and attributes for elements a, b, and c more than once? Doing so multiplies the amount of code, and requires diligence in ensuring that a, b, and c are defined identically in every ‘foo’ and ‘bar’.

回答1:

The short answer is yes you can.

class FieldsetParent extends Zend\Form\Fieldset
{
   public function init() {
        $this->add(array('name' => 'fieldA'));
        $this->add(array('name' => 'fieldB'));
        $this->add(array('name' => 'fieldC'));
   }
}

class FieldsetFoo extends FieldsetParent
{
   public function init() {

        parent::init();

        $this->add(array('name' => 'fieldD'));
        $this->add(array('name' => 'fieldE'));
        $this->add(array('name' => 'fieldF'));
        $this->add(array('name' => 'fieldG'));
   }
}

class FieldsetBar extends FieldsetParent
{
   public function init() {

        parent::init();

        $this->add(array('name' => 'fieldP'));
        $this->add(array('name' => 'fieldQ'));
        $this->add(array('name' => 'fieldR'));
        $this->add(array('name' => 'fieldS'));
   }
}