2013-02-19 111 views
1

我有一個工廠基於類像這樣:工廠模式設計

class AisisCore_Factory_Pattern { 

    protected static $_class_instance; 

    protected static $_dependencies; 

    public static function get_instance(){ 
     if(self::$_class_instance == null){ 
      $_class_instance = new self(); 
     } 

     return self::$_class_instance; 
    } 

    public static function create($class){ 
     if(empty($class)){ 
      throw new AisisCore_Exceptions_Exception('Class cannot be empty.'); 
     } 

     if(!isset(self::$_dependencies)){ 
      throw new AisisCore_Exceptions_Exception('There is no dependencies array created. 
       Please create one and register it.'); 
     } 

     if(!isset(self::$_dependencies[$class])){ 
      throw new AisisCore_Exceptions_Exception('This class does not exist in the dependecies array!'); 
     } 

     if(isset(self::$_dependencies[$class]['params'])){ 
      $new_class = new $class(implode(', ', self::$_dependencies[$class]['params'])); 
      return $new_class; 
     }else{ 
      $new_class = new $class(); 
      return $new_class; 
     } 
    } 

    public static function register_dependencies($array){ 
     self::$_dependencies = $array; 
    } 

} 

現在有了這個類,我們做到以下幾點:

首先設置我們的類列表及其相關

$class_list = array(
    'class_name_here' => array(
     'params' => array(
      'cat' 
     ) 
    ) 
); 

註冊他們:

AisisCore_Factory_Pattern::register_dependencies($class_list); 

這意味着,無論何時您調用create方法並將其傳遞給一個類,我們都會返回該類的新實例,同時也傳遞該類的任何參數。

創建的Clas

要創建一個類的所有我們要做的就是:

$object = AisisCore_Factory_Pattern::register_dependencies('class_name_here'); 

現在我們已經創建的類的一個新實例:class_name_here,並考取它的cat的參數,現在我們需要做的所有訪問其方法是做$object->method()

我的問題與所有這些是:

如果參數是數組會怎麼樣?我該如何處理?

一種解決方案可能是:

public static function create($class){ 

    if(isset(self::$_dependencies[$class]['params'])){ 
     if(is_array(self::$_dependencies[$class]['params'])){ 
      $ref = new ReflectionClass($class); 
      return $ref->newInstanceArgs(self::$_dependencies[$class]['params']); 
     } 
     $new_class = new $class(implode(', ', self::$_dependencies[$class]['params'])); 
     return $new_class; 
    }else{ 
     $new_class = new $class(); 
     return $new_class; 
    } 
} 
+0

你*可能*想看看'Zend \ Di',它基本上做你想重複的東西... https://github.com/ralphschindler/Zend_DI-Examples – Ocramius 2013-02-19 19:45:38

回答

0

你在這種情況下,最好的辦法是可能使用反射類來創建一個新的實例傳遞的參數在數組中。看到reflectionclass::newinstanceargs和 用戶評論也有類似的喜歡的東西:

$ref = new ReflectionClass($class); 
return $ref->newInstanceArgs(self::$_dependencies[$class]['params']); 

這個工作應該像call_user_func_array在陣列中的每個值作爲不同參數的函數傳遞。