phpooppdodatabase-abstraction

Database abstraction class design using PHP PDO


I am in the process of designing a web application (really, it's a hobby, and I'm trying to teach myself design, and what better way is there than doing it :). Anyway, I was thinking about how I would deal with my database. I am comfortable with PDO, and I was thinking of leveraging PDO in my abstraction class. I am thinking of making a singleton, so that there's only one database connection. This singleton would create a PDO connection.

After that, I fail to see why I would need to do too much else. I can then just use the database handler to call PDO functions. I may want some helper functions, but when it gets down to it, I would just use PDO for the actual SQL queries.

Is there something wrong with this approach? It seems overly simple compared to the abstraction classes I've used.


Solution

  • You don't need the Singleton.

    A database Singleton won't solve any concurrency issues. If anything, it can make sure you have only one PDO instance for the request it was created in. And it provides global access, which many people consider a bad thing. In addition you have to make some extra effort when testing the Singleton.

    Just create a wrapper that lazy connects and stores the instance when needed in your bootstrap and set the instance to your DAL supertype, for instance a TableDataGateway. Also, this way you don't limit yourself to only one PDO instance in case you will need a second one at some point.