Using PDO To Create A Data Access Object

4th August 2020 - 12 minutes read time

A Data Access Object (DAO) is a way of taking data out of a database or API and present it in a unified way across your application. As a design pattern this has uses in standardising how a particular bit of data is passed around, without having to resort to using arrays to accomplish the same job.

I was doing some work with PHP's PDO library the other day when I noticed that I could fetch data out of a database using the fetchAll() method with the PDO::FETCH_CLASS flag. This flag automatically returns the data in an object. This got me thinking more about how this worked, but I couldn't find many articles talking about this. Hence this post.

Setting Things Up

Let's take a class called SpecialText that will store an ID and some text, along with a __toString() method to allow the printing of those values. We will use this class throughout this post to store data from the database.