Factory Pattern

The Factory pattern is helpful in cases where you have several interchangeable classes and you need to choose one at runtime. To accomplish this, simply define a function that takes the class name as an argument and returns the instantiated class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class DatabaseFactory
{
    // The factory function takes as an argument the
    // name of the class to produce
    public static function getInstance($driver)
    {
        // Attempt to include the the file containing the class
        // (not necessary if you use a custom autoloader)
        if(include_once(dirname(__FILE__).'/drivers/database_'.$driver.'.php'))
        {
            // Build the name of the class, instantiate, and return
            $driver_class = 'Database_'.$driver;
            return new $driver_class;
        }
        else
        {
            throw new Exception('Database driver not found');
        }
    }
}

// To use, call the factory's static method:
$db = DatabaseFactory::getInstance('MySQL');

If you are using this pattern to connect to a database, you might make each class a Singleton.

To stay true to the principles of OOP, all classes instantiated by a factory should adhere to a specific interface.

Leave a Reply

You must be logged in to post a comment.