Thursday, June 5, 2008

Design Pattern in PHP: Factory pattern

The factory pattern is most interesting when Testing and Refactoring because one can substitute a class implementation for another without changing the core code.

In the example below, I have demonstrated a versatile factory method which sports object instance creation with a variable parameter list.

  • Base::factory( $className /*optional parameters*/ ) creates an object of class $className with, optionally, a list of parameters passed to the constructor
    • E.g. $object = Base::factory( 'TestClass', 'param1', 'param2' );
  • Base::mapClass( $sourceClassName, $targetClassName ) adds a mapping entry so that the factory builds an object instance of $targetClassName instead of $sourceClassName when asked to build for $sourceClassName
    • E.g. Base::mapClass( 'TestClass', 'TestDebugClass' );




Project
The project is located at GoogleCode.