0

I am trying to optimize my PHP code today and I want to setupd a singleton factory for PDO connections. Let me explain my current situation first.

I have a functions.php with a bunch of functions in it and at the top of almost every page I have

include 'functions.php';

Just like many do for their websites. One of these functions is my PDO connections, which looks like this:

function db_connect(){
$host = 'localhost';
$port = 3306; 
$database = 'mybigdb';
$username = 'user11';
$password = 'password1';

$dsn = "mysql:host=$host;port=$port;dbname=$database";

$db = new PDO($dsn, $username, $password);
return $db;
}

Within each of my functions that require a database connection, I will have something like this:

function fetch_row($param1, $param2, $db=NULL){
if(is_null($db))$db=db_connect();

//Rest of code here

}

That way I can pass along my database object, but have it added just in case it is not included. The code above works fine and I have been using it for a while. However, reading about Singleton Factory classes and thinking perhaps this is better.

I read this answer about Singleton factories but I am not quite sure how to use it. I am a nooby with classes and trying to learn. I have some questions...

  1. What would I put in the "..." where he has new ConnectionFactory(...); ?
  2. Where would I copy and paste the class code? Would I put it at the top of functions.php?
  3. What would I put at the beginning of each function? Should I still try and pass the database object through parameters?
  4. Is this method really worth converting too? Or is my current strategy Ok.

Thanks so much for an help :)

Community
  • 1
  • 1
kmoney12
  • 4,413
  • 5
  • 37
  • 59

1 Answers1

0

You can create a singleton like this.

class Connection {
  private static $_con = null;
  private function _constructor(){
      // here you instantiate de pdo conection
  }
  public static function GetInstace(){
      if ( self::$_con == null ) 
         self::$_con = new Connection();
      return self::$_con;
  }
}

After that you will do: $db = Connection::GetInstance();

Daedalus
  • 7,586
  • 5
  • 36
  • 61