Results 1 to 12 of 12
Thread: Database as a singleton?
May 18, 2009, 15:08 #1
- Join Date
- Oct 2005
- Milton Keynes, UK
- 9 Post(s)
- 2 Thread(s)
Database as a singleton?
For me there is no apparent difference between:
$db = db::getInstance(); $db->query('SELECT...');
apart from the extra line and (albeit tiny) extra memory needed for the extra defined variable. I can see that if you needed two instances of the database class, that it would be useful but I can't think of a single time when I'd need to do this. I'll never need to connect to more than one database.
Is there anything wrong with creating a map to the mysqli functions like this?
Before anyone starts an argument about rewriting inbuilt functions, there are several reasons I need to abstract them:
-Automated error handling for all queries
-My query function has logic for dealing with results from a stored procedure so I can just do $result = db::query('call stored_procedure();'); and it acts like a normal select.
-The query function accepts an array and does replacements on:
foreach ($params as $key => $value) $query = str_replace('%' . $key . '%', self::escape($value), $query);
n.b. The reason for allowing name value pairs is for multiple replacements. When joining lots of tables where the foreign key is indexed it's significantly faster if you add "AND fk=value" to the join line and the where line (in mysql at least)
Now, back to my question. From a design point of view, is this the best way of accessing my mapped database functions throughout the script.
I've read a little about dependency injection but this seems like overkill to me. So much has to be done from an efficiency and development time alone it doesn't seem worth it. I'm open to comments on this as perhaps i'm missing something vital but the overheads of this seem to heavily outweigh the mediocre gains.
My main thoughts are mapping the functions in a static class going to cause problems down the road? Would the singleton pattern be better? If so why?
Should I do something else entirely?