Search

PHP Design Patterns – Factory Pattern

The so called factory pattern is a pattern that creates other object for you, so you don’t manually instance them by using the new keyword.

Why do you want to do that? It’s not like there’s much work instantiate classes. Well, lets imagine that you have made a class Database that takes care of getting data from a MySql database. But the days pass and you use it everywhere in your code and all is well. Until you thinking about give your friend a copy of your code. The problem is that he hasn’t MySql installed on his server but uses a SqlLite database.

That means that he has to build his own class that exactly mimics your class, but with SqlLite functionality. And then hunt down every instantiation you made and switch that one for his. And what happeneds with other classes that he wants to switch to his own version.

The solution is to make a central place in your code where to instantiate and return that by reference.

Behold the factoryclass:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
< ?php
class Mysql implements Idatabase
{
	public function getRow()
	{
		return array ( 1, 'MySqlDog', 'black' );
	}
}
 
class SqlLite implements Idatabase
{
	public function getRow()
	{
		return array ( 1, 'SqlLiteDog', 'black' );
	}
}
 
interface Idatabase
{
	function getRow();
}
 
class factoryClass
{	
	public static function getClass( $classType )
	{
		$classes = array
		(
			'database' => 'SqlLite'
		);
 
		return new $classes[ $classType ];
	}
}
 
$DB = factoryClass::getClass( 'database' );
var_dump( $DB->getRow() );
?>

This factoryClass has access to a list of types of classes that the user then make requests for.
Why not use a array to hold the value and use $DB = new $classes[ $type ]?

Posted by Stig Lindqvist June 2008

Post A Comment

« « PHP Design Patterns – Introduction  ∞