HomePHP Storing Class Properties of Persistent Objects in MySQL Tables
Storing Class Properties of Persistent Objects in MySQL Tables
Welcome to the fifth part of a six-part series that shows you how to build persistent objects in PHP 5. In this part of the series, I'll show you how to develop a persistent class that can save its properties to a MySQL table.
Frankly speaking, creating objects in PHP 5 that are capable of maintaining their state through several HTTP requests is a pretty simple task, certainly much easier than you might have thought. In general terms, the entire creation process is reduced to defining a class that has some kind of storage mechanism associated with it. That’s it.
In most cases, that mechanism will be comprised of one or more MySQL tables, given the long and tight relationship that exists between this RDBMS and the language. It's also feasible to use cookies or simple text files to store string-based representations of objects instead, which can be retrieved and restored at a later time for further processing.
Naturally, all of these theoretical concepts must be properly backed up with a decent number of functional code samples. For instance, in the previous episode of the series I went through the development of a basic class which could save its properties to a specified text file via a simple implementation of its destructor.
Undeniably, the major benefit in defining a class like this was the possibility of fetching the values assigned to those properties (and even assign new ones) on a different web page. This demonstrated in a nutshell the concept of a persistent class, or expressed more accurately, a persistent object.
Nonetheless, as I mentioned a few moments ago, the most common mechanism used by PHP 5 objects to maintain their state across a number of HTTP requests is a MySQL database table. Thus, in this penultimate tutorial of the series I’m going to show you how to define a class that will save its properties to such a table, thus exploring yet another approach to building persistent objects with PHP 5.
Now, it’s time to get rid of the preliminaries and start learning how to tie a simple class to a MySQL database. Let’s get going!