나는 이와 같은 공장을 기반으로 클래스가 :공장 패턴 디자인
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;
}
}
당신은 * 반복적으로 시도하고있는 것을하는'Zend \ Di'를보고 싶을 것입니다 ... https://github.com/ralphschindler/Zend_DI-Examples – Ocramius