我有一个基于工厂的类,例如:
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 方法并将其传递给一个类,我们将返回该类的一个新实例,同时还传递该类的任何参数。
创建一个类
要创建一个类,我们要做的就是:
$object = AisisCore_Factory_Pattern::register_dependencies('class_name_here');
现在我们已经创建了一个新的 class: 实例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;
}
}