I maintain and add features on a freelance basis to a website written in PHP. The application was started in PHP4 by a junior programmer back in 2006, and features some very insecure and unmaintainable ways of doing things, which I am trying to correct as time goes on. If the client agrees, one of the first things I would like to do is add in a proper database layer of some sort.

These two functions are basically the database layer, and SQL queries are constructed on the fly for them all over the place.

So my question is, how can I start to introduce database abstraction in to the mix? I would like to move to PDO for security and ease of use reasons, but maybe there is a better way to go?

I have already moved the project to Composer for some of its dependencies (Some are dead projects, which is a different issue) so maybe an ORM like Doctrine would be the way to go? That might mean moving the website to OOP in one go though: a daunting prospect, and a sure no-go from the client.

3 Answers
3

It looks like you lucked out in that the original developer put in a 'wrapper' function to handle mysql_* queries. This is far better than having 15,000 mysql_query() calls spread through the code. I'd change those functions ('my_query', 'spawnarray') to use PDO as a first step. Then, once you are completely off mysql_*, start switching everything over to PDO if its worth the time for you (ie, depending on the importance/expected lifespan of the app in question).

I would suggest looking to decouple the data layer from the business logic of your application through a pattern like DAO.

Once the persistence layer is properly decoupled (and testable), you can choose the appropriate implementation for your specific needs. As long as the data layer is abstracted, that choice can be deferred and you can always swap it out with a more appropriate implementation if your needs change.

You can also use Zend Framework's Zend\Db, as you go. You don't need to have a major overhaul to implement it, you can start using it for new code only. When the client approves, you can start converting old code to use Zend\Db too. This way you're not adding some more piece of code to maintain, just use off the shelf component.

The advantage is not only you will replace the old database layer, you will also be able to 'lift' the implementation to use higher level concept such as the Table Gateway and Row Gateway, both are supplied in Zend\Db.

Same reason can be said about Doctrine too, you can use it where you want it, although it is heavier than Zend\Db. It depends on the problems you want to solve too, e.g. do you need Domain Model.