1

Im currently getting my hands dirty with some subclassing object oriented php. I would like to use an array to create some form fields, and these fields are separated into classes based on their type. This means that I have a main class called "form_field", and then have a bunch of subclasses called "form_field_type" (ex. "form_field_select"). The idea is that each subclass "knows" how to best generate their HTML in a display method.

So lets say that i write an array like this:

$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,
    )
);

I would then like to create a loop that instantiates the correct class based on the type:

foreach ($fields as $field) {
    $type = $field['type'];

    $new_field = // instantiate the correct field class here based on type

    $new_field->display();
}

What would be the best approach here? I would like to avoid doing something like:

if ($type == 'text') {
    $new_field = new form_field_text();
} else if ($type == 'select') {
    $new_field = new form_field_select();
} // etc...

This just feels inefficient, and i feel like there must be a better way? Is there a good pattern that is generally used in this situation, or am I going about solving this the wrong way?

2
  • 1
    I think you should take a look on the factory design pattern. Commented Sep 21, 2014 at 14:38
  • Possible duplicate: stackoverflow.com/questions/4578335/… Commented Sep 21, 2014 at 14:45

1 Answer 1

1

Try something like this...

foreach ($fields as $field) {
    $type = $field['type'];

    // instantiate the correct field class here based on type
    $classname = 'form_field_' .$type;
    if (!class_exists($classname)) { //continue or throw new Exception }

    // functional
    $new_field = new $classname();

    // object oriented
    $class = new ReflectionClass($classname);
    $new_field = $class->newInstance();

    $new_field->display();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.