Scarface
Scarface

Reputation: 3913

singleton factory connection pdo

Hey guys I am having a lot of trouble trying to understand this and I was just wondering if someone could help me with some questions. I found some code that is supposed to create a connection with pdo. The problem I was having was having my connection defined within functions. Someone suggested globals but then pointed to a 'better' solution Global or Singleton for database connection?. My questions with this code are:

  1. What is the point of the connection factory? What goes inside new ConnectionFactory(...)

  2. When the connection is defined $db = new PDO(...); why is there no try or catch (I use those for error handling)? Does this then mean I have to use try and catch for every subsequent query?

Here's the code:

class ConnectionFactory
{
    private static $factory;
    public static function getFactory()
    {
        if (!self::$factory)
            self::$factory = new ConnectionFactory(...);
        return self::$factory;
    }

    private $db;

    public function getConnection() {
        if (!$db)
            $db = new PDO(...);
        return $db;
    }
}

function getSomething()
{
    $conn = ConnectionFactory::getFactory()->getConnection();
    .
    .
    .
}

Upvotes: 0

Views: 2365

Answers (1)

selfawaresoup
selfawaresoup

Reputation: 15832

You seem a little confused about the topic of design patterns like the factory. Maybe you should read a book or some tutorials about design patterns in general or common patterns for PHP first. Just google "php design patterns". There are plenty of resources out there on that subject.

But to answer your question briefly:

  1. A Connection Factory is used to produce connection objects independently of the actual underlying database. A simple PDO factory would manage the assembly of the DSN connection strings that PDO needs based on the parameters you pass to it and return a ready to use PDO object.

  2. In most cases it is useful to build more sophisticated database adapter classes that provide error handling themselves along with more comfortable ways of executing queries. Again, a factory class can then be used to produce the correct connection object according to your database system.

Upvotes: 3

Related Questions