HomePHP Page 3 - Polymorphism, Design Patterns, and PHP Programming
The Factory Pattern - PHP
Last week, we continued our discussion of the object-oriented features of PHP 5 by taking a first look at design patterns. This week, we will continue looking at design patterns, and examine polymorphism. This article, the third of four parts, is excerpted from chapter two of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).
The Factory pattern provides a standard way for a class to create objects of other classes. The typical use for this is when you have a function that should return objects of different classes, depending on its input parameters.
One of the major challenges in migrating services to a different database is finding all the places where the old wrapper object is used and supplying the new one. For example, say you have a reporting database that is backed against an Oracle database that you access exclusively through a class called DB_Oracle_Reporting:
class DB_Oracle_Reporting extends DB_Oracle { /*
... */}
and because you had foresight DB_Oracle uses our standard database API.
class DB_Oracle implements DB_Connection { /* ...
*/ }
Scattered throughout the application code, whenever access to the reporting database is required, you have wrapper instantiations like this:
$dbh = new DB_Oracle_Reporting;
If you want to cut the database over to use the new wrapper DB_Mysql_Reporting, you need to track down every place where you use the old wrapper and change it to this:
$dbh = new DB_Mysql_Reporting;
A more flexible approach is to create all your database objects with a single factory. Such a factory would look like this:
function DB_Connection_Factory($key)
{
switch($key) {
case "Test":
return new DB_Mysql_Test;
case "Prod":
return new DB_Mysql_Prod;
case "Weblog":
return new DB_Pgsql_Weblog;
case "Reporting":
return new DB_Oracle_Reporting;
default:
return false;
}
}
Instead of instantiating objects by using new, you can use the following to instantiate objects:
$dbh = DB_Connection_factory("Reporting");
Now to globally change the implementation of connections using the reporting interface, you only need to change the factory.