PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

Advanced OOP With SPL In PHP 5

Creating a Database Factory

At this point you might be asking yourself how this abstracts the interface if you have to create a bunch of new PostgreSQL objects. To solve this we use the Factory pattern, which is defined as follows:

Listing 3 DatabaseFactory.php
<?php
    /**
     * DatabaseFactory
     *
     * Creates an IDataBaseBindings object for use from the application layer
     *
     * @depends    PostgreSQL, MySQL
     */
    class DatabaseFactory
    {
        /**
         * factory
         *
         * Returns an IDataBaseBindings compatible object based on the type of database
         * defined in $configuration['databasetype']
         */
        public static function factory()
        {
            switch($configuration['databasetype']) {
                case 'PostgreSQL':
                    return new PostgreSQL();
                    break;
                case 'MySQL':
                    return new MySQL();
                    break;
                default:
                    throw new Exception('Database implementer not found');
            }
        }
    }
?>

The above code provides a unified access point to create your interface compatible objects for use within the application code.

This ensures that your application does not know, or care about what database it is using, only that it meets the requirements defined in the interface.

In This Article