HomePHP Page 2 - Building Object-Oriented Database Interfaces in PHP: Processing Data through Data Access Objects
Overview of a database interface class: defining general guidelines - PHP
With websites now featuring full-blown dynamic applications that link to databases, data accessing has become a critical process. Often, an object-oriented solution is wanted to manage the data access operations. This works well, except when certain statements are hard-coded in that can cause headaches when a update is required. Alejandro Gervasio explains how a new category of tools, known as database interfaces, help to solve this problem.
It's important to know some general guidelines before designing a database interface class. First, the class will be a logical representation of the database table structure with which it will be associated. In a few words, this means that each one of the table fields will be represented inside the class as data members, exposing the corresponding modifiers and accessing methods (in programming parlance, setters and getters).
However, instead of coding directly the DB interface, I'll delegate the hard work to another class that I'll call "DBIGenerator." This class will behave as the "object factory" to generate each DB interface, taking advantage of the capacity offered by the "Factory" design pattern. Just in case you want to learn more about design patterns, the PHP manual contains a good introduction covering the subject. As usual, the Web is the best resource for finding good tutorials and articles treating the topic.
After going through the preliminaries of how to build a database interface, let's start defining the core logic for the "DBIGenerator" class. As its name clearly suggests, it will be responsible for creating a database interface class, based on a few basic parameters: the name of the database interface and the file system path where the class will be created.
In our first approximation designing the "DBIGenerator" class, we'll assume that we're directly working with a hypothetical "users" database table that contains an ID field of type "AUTO_INCREMENT", and three string-type fields to store "First Name", "Last Name" and "email" values. As I said before, this will be changed at a later time, when I code the final version of the class, so you don't have to worry about it. But now, let's see the list for the "DBIGenerator" class, and next, break down the code, to understand the corresponding explanations in detail. So, keep reading to see how the class looks.