views:

208

answers:

1

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 http://stackoverflow.com/questions/130878/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();
    .
    .
    .
}
+1  A: 

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.

Techpriester
thanks tech yes I was quite confused having never even heard of something like a singleton or factory. I did not know they were called design patterns, thanks for that. With regards to my questions, do you know of any examples I could look at or good resources before I dive into this?
Scarface
As I said, Google will throw up more than enough tutorials on this and I'm sure there are good examples here on stackoverflow as well. There's also a book called "PHP Design Patterns" released by O'Reilly that may be useful.
Techpriester
thanks I will see if I can find it
Scarface