【发布时间】:2014-11-15 14:29:04
【问题描述】:
我目前正在使用一些面向对象的子类化 php。我想使用一个数组来创建一些表单字段,这些字段根据它们的类型分为类。这意味着我有一个名为“form_field”的主类,然后有一堆名为“form_field_type”的子类(例如“form_field_select”)。这个想法是每个子类“知道”如何在显示方法中最好地生成它们的 HTML。
假设我写了一个这样的数组:
$fields = array(
array(
'name' => 'field1',
'type' => 'text',
'label' => 'label1',
'description' => 'desc1',
'required' => true,
),
array(
'name' => 'field2',
'type' => 'select',
'label' => 'label1',
'description' => 'desc1',
'options' => array(
'option1' => 'Cat',
'option2' => 'Dog',
),
'ui' => 'select2',
'allow_null' => false,
)
);
然后我想创建一个循环,根据类型实例化正确的类:
foreach ($fields as $field) {
$type = $field['type'];
$new_field = // instantiate the correct field class here based on type
$new_field->display();
}
这里最好的方法是什么?我想避免做类似的事情:
if ($type == 'text') {
$new_field = new form_field_text();
} else if ($type == 'select') {
$new_field = new form_field_select();
} // etc...
这只是感觉效率低下,我觉得必须有更好的方法?在这种情况下是否有一个很好的模式,或者我打算以错误的方式解决这个问题?
【问题讨论】:
-
我觉得你应该看看工厂设计模式。
标签: php oop dynamic instance subclass