次のようなファクトリベースのクラスがあります。
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
そのメソッドにアクセスするために必要なことは do だけです$object->method()
これに関する私の質問は次のとおりです。
パラメータが配列の場合はどうなりますか? どうすれば対処できますか?
1つの解決策は次のとおりです。
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;
}
}