PHP and PDO – Use it!

A lot of novice programmers exploring object orientation get their feet wet by implementing a database abstraction class. It’s a good learning assignment, but has no more use in production code ever since PHP introduced PDO.

Mostly I see them for MySQL, Google finds ~10 million results for “php mysql class”, but there’s also a few to be found for any other, for example googling “php sqlite class” returns ~1 million results.

This is a pretty good indicator that:

  1. PHP and MySQL is used a lot together (but you already knew that ;)
  2. Many PHP programmers think an object oriented abstraction for database access is a good idea.

I wholeheartedly agree to the second point, but I fear this abundance of (quite) similar database classes and the ubiquity of search results for them, could paint a (very) wrong picture and bring about some bad practices.

Judging by these search results, one could assume that PHP has no database abstraction. And that one either has to roll-their-own or download one from the web.

But one of the new features of PHP 5 (5.1 to be exact) was the introduction of PDO, the PHP Data Objects extension. It is slightly more than just a database abstraction, but that’s currently its main use. It might seem a bit cumbersome at first – the “weird” connection string, the slightly different query or execute methods and their return results, or that transaction stuff (commit, rollback). But once you’ve read yourself into it and played around some, you’ll see that there is no need at all for some random or self-written database abstraction class in professional code.

So if you start a new project, and use PHP >= 5.1, I urge you not to use some database class but instead start using PDO. I would even go so far and call anything else reckless and irresponsible but that’s just me.

Code you didn’t write is bugs you didn’t create.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: