工厂模式设计
问题描述:
我有一个工厂基于类像这样:工厂模式设计
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;
}
}
答
你在这种情况下,最好的办法是可能使用反射类来创建一个新的实例传递的参数在数组中。看到reflectionclass::newinstanceargs和 用户评论也有类似的喜欢的东西:
$ref = new ReflectionClass($class);
return $ref->newInstanceArgs(self::$_dependencies[$class]['params']);
这个工作应该像call_user_func_array在阵列中的每个值作为不同参数的函数传递。
你*可能*想看看'Zend \ Di',它基本上做你想重复的东西... https://github.com/ralphschindler/Zend_DI-Examples – Ocramius 2013-02-19 19:45:38