2014-09-21 3 views
1

현재 일부 하위 클래스 객체 지향 PHP로 내 손이 더러워지고 있습니다. 배열을 사용하여 양식 필드를 만들고이 필드는 유형에 따라 클래스로 구분됩니다. 즉, "form_field"라는 기본 클래스가 있고 "form_field_type"(예 : "form_field_select")이라는 하위 클래스가 있습니다. 아이디어는 각 하위 클래스가 표시 방법에서 HTML을 가장 잘 생성하는 방법을 "알"있습니다.PHP에서 문자열을 기반으로 클래스를 동적으로 인스턴스화

그래서 나는이 같은 배열을 작성하는 것이 말할 수 :

$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... 

이 단지 비효율적 인 느낌을, 나는 더 나은 방법이있을 것 같은 느낌? 이 상황에서 일반적으로 사용되는 좋은 패턴이 있습니까? 아니면 잘못된 방식으로 해결할 것입니까? 이 같은

+1

난 당신이 공장 디자인 패턴을 살펴한다고 생각합니다. – Sascha

+0

가능한 중복 : http://stackoverflow.com/questions/4578335/creating-php-class-instance-with-a-string – algorhythm

답변

1

시도 뭔가 ...

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(); 
} 
관련 문제