Design pattern in PHP: Factory Method Pattern

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.

What problems can it solve?

The Factory Method Pattern solves the problem of how to create object instances which inherit from a same abstract class and hide its complexity, especially when constructor is complicated. Client codes don’t need to know the implementation of the constructor.

What factory method pattern can do?

Object-oriented design emphasizes the abstract class over the implementation. We have to work with generalizations rather than specializations as far as we can. In factory method pattern, an object is created in a factory method or a factory class in which accomplish object instantiation and maybe some extra actions for this new object.

Implementation

Here is a database-select situation showing how to use factory method pattern in PHP.

Step 1: Create abstract product class

/**
 * abstract db prduct
 */
abstract class Database
{
	abstract public function connect($host, $ip);

	public function select($sql)
	{
		echo "excute sucess";
	}
}

Step 2: create 2 concrete db product class which inherit above abstract class.

/**
 * concrete product: mysql
 */
class Mysql extends Database
{
	
	public function connect($host, $ip)
	{
		echo "mysql connect sucess\n";
	}
}

/**
 * concrete product: oracle
 */
class oracle extends Database
{
	
	public function connect($host, $ip)
	{
		echo "oracle connect sucess\n";
	}
}

Step 3: create abstract factory class.

/**
 * abstract facroty
 */
abstract class DatabaseFacory
{
	abstract public function getDb();	
}

Step 4: create concrete factory class for each of 2 concrete product class.

/**
 * concrete mysql facroty
 */
class MysqlFacory extends DatabaseFacory
{
	
	public function getDb()
	{
		$mysql = new Mysql();
		$mysql->connect('127.0.0.1', 6379);
		// do something if you want

		return $mysql;
	}
}

/**
 * concrete oracle facroty
 */
class OracleFactory extends DatabaseFacory
{
	public function getDb()
	{
		$oracle = new Oracle();
		$oracle->connect('127.0.0.1', 1521);
		// do something if you want

		return $oracle;
	}
}

Step 5: do some test

$mysqlFacory = new MysqlFacory();
$mysql = $mysqlFacory->getDb();

$oracleFactory = new OracleFactory();
$oracle = $oracleFactory->getDb();

Step 6: run the script and check the result.

$ php factorymethod.php
mysql connect sucess
oracle connect sucess

In above example, we can replace MySQL with Oracle and the versa. What’s more, we don’t need to know how to connect a MySQL or Oracle, we just change the factory and use it.

RSS