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 メソッドを呼び出してクラスを渡すと、そのクラスの新しいインスタンスが返され、そのクラスのパラメーターも渡されます。

クラスを作成する

クラスを作成するには、次のようにします。

$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;
    }
}
4

1 に答える 1

0

この状況での最善の策は、おそらくリフレクション クラスを使用して、引数の配列を渡す新しいインスタンスを作成することです。Reflectionclass::newinstanceargsを参照してください。ユーザーのコメントには次のようなものがあります。

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

これは、配列内の各値が異なる引数として関数に渡されるという点で、call_user_func_arrayのように機能するはずです。

于 2013-02-19T19:40:10.090 に答える