Database abstraction | Rickard Andersson

Database abstraction

Most modern PHP web applications these days use some kind of database abstraction/adapter class (or collection of functions). The most obvious benefit of abstracting database communication is that one can, at least in theory, just drop in a new script file to support a new database. There are more benefits though. I’m thinking of one in particular. I was recently hired to investigate what was causing an unnamed web application to perform horribly. My plan of attack was to have a look at the queries that the web app was sending to MySQL and to measure the time it took to execute each of these queries. Naturally, I started to look for some kind of database class, but I didn’t find one. As it turns out, the web app in question does not abstract it’s communication with MySQL. What this means is that I have a couple of hundred kilobytes of source code completely littered with calls to mysql_query() and as far as I know, there is no way in PHP to “override” a function like mysql_query(). One solution is of course to search-and-replace all calls to mysql_query() with some custom function, but the web app is comprised of a lot of files and is live and very tightly integrated into the website on which it runs. I don’t want to screw something up. What I thought would be an hour or two just turned into a much larger job.

I hereby forbid anyone to write any kind of PHP database code that does direct calls to the database extension functions. If you’re gonna talk to a database from your PHP script, please do that via some kind of function library or adapter class. You’ll be saving yourself and any anyone else that might end up working on the script in the future, a whole lot of work.

Ranting developer, out.

Post a Comment

Comments are moderated. Your email is never published nor shared.