Monday, 15 April 2013

php - Factory pattern Design -



php - Factory pattern Design -

i have mill based class such this:

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(); } homecoming self::$_class_instance; } public static function create($class){ if(empty($class)){ throw new aisiscore_exceptions_exception('class cannot empty.'); } if(!isset(self::$_dependencies)){ throw new aisiscore_exceptions_exception('there no dependencies array created. please create 1 , register it.'); } if(!isset(self::$_dependencies[$class])){ throw new aisiscore_exceptions_exception('this class not exist in dependecies array!'); } if(isset(self::$_dependencies[$class]['params'])){ $new_class = new $class(implode(', ', self::$_dependencies[$class]['params'])); homecoming $new_class; }else{ $new_class = new $class(); homecoming $new_class; } } public static function register_dependencies($array){ self::$_dependencies = $array; } }

now class following:

first set our class list , dependencies

$class_list = array( 'class_name_here' => array( 'params' => array( 'cat' ) ) );

register them:

aisiscore_factory_pattern::register_dependencies($class_list);

this means time phone call create method , pass class homecoming new instance of class, while passing in parameters class.

create clas

to create class is:

$object = aisiscore_factory_pattern::register_dependencies('class_name_here');

and have created new instance of class: class_name_here , pasing parameter of cat, , have access methods $object->method()

my question is:

what if parameter array? how deal that?

one solution be:

public static function create($class){ if(isset(self::$_dependencies[$class]['params'])){ if(is_array(self::$_dependencies[$class]['params'])){ $ref = new reflectionclass($class); homecoming $ref->newinstanceargs(self::$_dependencies[$class]['params']); } $new_class = new $class(implode(', ', self::$_dependencies[$class]['params'])); homecoming $new_class; }else{ $new_class = new $class(); homecoming $new_class; } }

your best bet in situation utilize reflection class create new instance passing in array of arguments. see reflectionclass::newinstanceargs , user comments has similar like:

$ref = new reflectionclass($class); homecoming $ref->newinstanceargs(self::$_dependencies[$class]['params']);

this should work call_user_func_array in each value in array passed different argument function.

php arrays parameters factory-pattern

No comments:

Post a Comment