我有一个Zend\Form\Element
实例,我需要array
从该实例中提取所有配置,序列化并在某处持久保存,稍后在表单元素工厂中重新使用以再次生成类似的实例。
是否存在任何编程方式来从zend Framework 2中已实例化的表单元素对象中获取完整的配置签名?
最简洁的答案是不; 您将不得不自己动手。
您可以创建一个独立的类,该类可以接受任何元素并通过读取其公共方法返回正确的数组;这实际上是在逆转的功能FormFactory
。
一个非常简单的例子
class FormElementSerializer
{
public function toArray(ElementInterface $element)
{
$spec = $this->getElementSpec($element);
if ($element instanceof FieldsetInterface) {
$spec = $this->getFieldsetSpec($element, $spec);
}
if ($element instanceof Form) {
$spec = $this->getFormSpec($element, $spec);
}
return $spec;
}
protected function getElementSpec(ElementInterface $element)
{
$spec = array(
'type' => $this->getElementType($element),
'name' => $element->getName(),
'options' => $element->getOptions(),
'attributes' => $element->getAttributes(),
);
return $spec;
}
protected function getFieldsetSpec(FieldsetInterface $fieldset, array $spec)
{
foreach($fieldset->getElements() as $element) {
$spec['elements'][] = $this->getElementSpec($element);
}
return $spec;
}
// deals with hydrators, fieldsets etc
protected function getFormSpec(FormInterface $form, array $spec);
// could be as simple as returning the class name
protected function getElementType(ElementInterface $element);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句