The factory pattern is a simple but powerful design pattern which makes it very easy to manage and maintain plenty of classes.
The factory pattern, as it means, is using some material to provide products. But what we call the factory pattern here is to create the objects by assigning parameters to the producer class. In fact the very basical function such as print() is the brief explanation of factory.
Now let’s take a look at Zend_Cache module and its explanation of factory pattern :
The source code of Zend_Cache below is simplified in order to keep clear :
abstract class Zend_Cache
// Standard frontends
public static $standardFrontends = array([…]);
// Standard backends
public static $standardBackends = array([…]);
// Standard backends which implement the ExtendedInterface
public static $standardExtendedBackends = array([…]);
* @param mixed $frontend frontend name (string) or Zend_Cache_Frontend_ object
* @param mixed $backend backend name (string) or Zend_Cache_Backend_ object
* @return Zend_Cache_Core|Zend_Cache_Frontend
public static function factory($frontend, $backend, […])
$backendClass = ‘Zend_Cache_Backend_’ . $backend;
$backendObject = new backendClass;
$frontendClass = ‘Zend_Cache_Frontend_’ . $frontend;
$frontendObject = new frontendClass;
We should pay attention to the fact that Zend_Cache is declared with abstract which means it’s an abstract class. This makes it impossible to be instantiated and only be used as a factory that provide objects you need. This is an effective mechanism to prevent mess from misapply the factory.
In the other hand, we can also see some static variables such as $standardFrontends which can be seen as the quality standard of the products. These standards are easy to maintain. Users can use or modify them everytime and everywhere.
Here are the products which Zend_Cache provides :
All the Zend_Cache_Frontend_Xxx are inherited from Zend_Cache_Core :
class Zend_Cache_Frontend_Output extends Zend_Cache_Core
class Zend_Cache_Frontend_Function extends Zend_Cache_Core
class Zend_Cache_Frontend_File extends Zend_Cache_Core
class Zend_Cache_Frontend_Class extends Zend_Cache_Core
class Zend_Cache_Frontend_Page extends Zend_Cache_Core
We can get the instance of cache frontend by using the following code :
// We choose a backend (for example 'File' or 'Sqlite'...) $backendName = '[...]'; // We choose a frontend (for example 'Core', 'Output', 'Page'...) $frontendName = '[...]'; // We set an array of options for the choosen frontend $frontendOptions = array([...]); // We set an array of options for the choosen backend $backendOptions = array([...]); // We create an instance of Zend_Cache // (of course, the two last arguments are optional) $cache = Zend_Cache::factory($frontendName, $backendName, $frontendOptions, $backendOptions);
The factory is the strong guarantee for the maintenance of framework. You can find it everywhere within the Zend Framework.