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...
- What would I put in the "..." where he has new ConnectionFactory(...); ?
- Where would I copy and paste the class code? Would I put it at the top of functions.php?
- What would I put at the beginning of each function? Should I still try and pass the database object through parameters?
- Is this method really worth converting too? Or is my current strategy Ok.
Thanks so much for an help :)