View Full Version : Am I using the factory pattern correctly?

10-18-2012, 08:36 PM
Hello, I am currently investigating the factory pattern and think I understand it, but just want to make sure I am doing it right with my connection example below for different ways of connecting to a database.

1 - First of all I have set the type of connection I want in this case a PDO one

$connection = dbConnectionFactory::getConnection('pdo');

2- Use a factory to use the approprate connection

class dbConnectionFactory {
public function getConnection($type) {
switch($type) {
case 'pdo': Return PDOConnection::myConn(); break;
case 'mysql': Return MYSQLConnection::myConn(); break;
case 'mysqli': Return MYSQLiConnection::myConn(); break;

3 - Then grab the PDOConnection from the factory. This then loads myConn() which is a basic singleton pattern, which returns one single instance

So my question is in the above am I using it right for a factory pattern or have I misunderstood? Any improvements on this and the way I connect that anyone can advise/suggest?

Thank you

10-18-2012, 10:51 PM
The only thing that's wrong is that getConnection needs to be static. Without it, it will be triggering an E_STRICT error on access, but I *believe* it will still function properly. Same goes for the singleton's as well; make sure the myconn is static and returning a static instance stored either local to the class, or local to the static method (I wouldn't do the latter unless you are using a trait instead).