Design patterns: The Factory
Friday, 10. August 2007, 15:04:57
In this post I'll explain the concept of the factory a bit further and provide an example view factory implementation for you. We also brush the singleton pattern a bit.
Despite the fancy name, the factory pattern is actually very simple and you may even have used it before even knowing about the fancy name.
A factory is used to build instances of some other class, as you migth have expected from the name. This way you can make it easier to configure complex objects such as Zend_View's or Smarty's.
If you think about configuring a Smarty object:
$smarty = new Smarty(); $smarty->compile_dir = './template_c'; $smarty->plugin_dir[] = './plugins'; $smarty->template_dir = './templates'; //etc.
So that's quite much stuff to do. Now, if you had to create more than one Smarty instance you would need to copypaste the code and repeating the same code in many places is not good practice.
How about using a factory to churn out these objects for us?
First we need to configure our factory:
$viewFactory = CU_ViewFactory::getInstance();
$viewFactory->setViewClass('CU_View_Smarty')
->setConfig(array(
'compileDir' => './template_c',
'helperPath' => './application/views/helpers',
'pluginDir' => './plugins'
));
After the factory has been configured, creating a new view is as easy as...
$view = CU_ViewFactory::getInstance()->createView();
Simple, isn't it? This example is taken from the CMS system I'm building for my site, CodeUtopia, so you can probably guess where the CU comes from.
Here is the full code for the view factory class
class CU_ViewFactory
{
private $_config;
private $_viewClass;
private static $_instance;
private function __construct()
{
}
public static function getInstance()
{
if(!CU_ViewFactory::$_instance)
CU_ViewFactory::$_instance = new CU_ViewFactory();
return CU_ViewFactory::$_instance;
}
public function setConfig($config)
{
$this->_config = $config;
return $this;
}
public function setViewClass($viewClass)
{
$this->_viewClass = $viewClass;
return $this;
}
public function createView()
{
$view = new $this->_viewClass($this->_config);
$view->assign('PATH',dirname($_SERVER['SCRIPT_NAME']));
return $view;
}
}
This factory uses the singleton pattern, which means that there can be only one instance of the class. This is ensured by declaring the constructor function private which effectively means that you can't do new CU_ViewFactory outside the class itself. To get an instance of the factory, we define a static function called getInstance() which handles creating the first instance and returning it.
I hope this demonstrated the factory pattern and the view factory so that it was easy to understand. If you have any questions or comments, the box is below.







zomg # 30. August 2007, 05:18