Login

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!

{mospagebreak title=Review: saving class properties to a text file}

Before I proceed to explain how to build a sample class that can save its properties to a simple MySQL database table, first I’d like to reintroduce the example developed in the previous installment of this series. It was aimed at demonstrating how to create a similar class whose corresponding properties were stored in a specified text file.

So here’s the complete definition of the aforementioned sample class. Pay close attention to it, please:

Aside from implementing the “__set()” and “__get()” PHP 5 magic methods, which allow you to overload easily any number of undeclared properties, the two true workhorses of the previous “User” class are its constructor and destructor methods. The first one takes care of retrieving the values assigned to those properties, while the second one saves them to a determined text file, which has been passed previously as an incoming argument.

Without a doubt, the definition of this example class not only should provide you with the right pointers to start creating your own persistent classes, but it should give you a clear idea of the actual power in using magic methods to perform numerous tasks behind an extremely simple API.

Now that you’ve surely grasped how this sample class does its thing, below I included a script that shows how to use an instance of it in a concrete case. Study the following code fragment:

// example on creating a persistent object

$user = new User(‘newfile.txt’);

$user->name = ‘Alejandro';

$user->email = ‘alejandro@mydomain.com';

// __destruct() saves automatically the object to the target file

As I said before, thanks to the flexible nature of the “User” class, it’s extremely simple to spawn a user object, dynamically create a couple of properties, and then save them to a specific text file — in this case named “newfile.txt.”

Naturally, the object’s destructor is responsible for storing the properties in the target file, right before the PHP interpreter finishes executing the script.

On the other hand, it’s possible to restore those properties or assign new values to them in a different file, provided that the definition of the “User” class has been included previously. This last task is performed by the following script:

// assign new properties to the persistent object

$user = new User(‘newfile.txt’);

$user->name = ‘Mary';

$user->email = ‘mary@domain.com';

// __destruct() saves automatically the object to the target file

Simple to code and read, isn’t it? As you can see, the properties of the user object created in a previous file are assigned a pair of brand new values, which are again saved to the target text file, thus showing how they can persist across different HTTP requests.

So far, everything looks good; you’ve learned how to create persistent classes that maintain their state by means of a plain text file. So, what’s the next step to take? Well, as I explained at the beginning of this tutorial, in most cases the storage mechanism used by persistent classes in PHP 5 is simply a MySQL table.

Therefore, in the following section I’m going to build a basic MySQL abstraction class, which will be utilized by a persistent object to save its properties for further manipulation.

Now, if you wish to see how this brand new MySQL-accessing class will be defined, click on the link below and keep reading.

{mospagebreak title=Creating a MySQL abstraction class}

While this may sound obvious, to build a persistent class that will save its properties to a MySQL database table, it’s first necessary to create an interface that permits it to access that table in a straightforward way. In this case, the element that will play that role will be a basic MySQL abstraction class whose definition will look as follows:

The above “MySQL class” does a decent job when it comes to performing queries, counting rows in result sets and finding insertion IDs. Though it isn’t suitable for production environments, this sample class encapsulates enough functionality to perfectly fit the needs of a persistent class that will store its properties in a database table.

Thus, having at our disposal a class that allows you to abstract access to MySQL tables in a pretty respectable way, the only thing that remains undone is building the class that will persist through several HTTP requests.

But guess what? This class will be defined in the last section of this article. Therefore, please read the new few lines.

{mospagebreak title=Building a database-driven persistent class}

To demonstrate how to build a persistent class that will store its properties in a MySQL table, I’m going to redefine the “User” class utilized in this article and in previous ones, which hopefully will make this development process much easier to understand for you.

Having clarified that point, here’s the new definition of the aforementioned class, which now looks like this:

As I explained earlier, the skeleton of this “User” class remains nearly the same as its previous versions, except for its constructor and destructor methods, which are the ones that actually do the dirty work. The first method is responsible for retrieving the properties of the class from a specified MySQL table, while the second one is tasked with saving them back.

In this specific example, I used the term “retrieving” on purpose because the constructor uses an injected instance of the MySQL class defined previously to retrieve the properties from a fictional “users” MySQL table according to the supplied ID. On the other hand, the destructor simply updates the corresponding table record with new data, in case the properties have been updated as well.

Of course, the best way to understand how the above persistent class functions is by way of a concrete example, but this will be created in the last part of the series. Anyway, I guess that at this point you have a clear idea of how to spawn a persistent object by using the two classes defined before. So, if you feel this will be a no-brainer process, then go for it!

Final thoughts

In this penultimate part of the series, I went through the development of a persistent class that had the ability to save its properties to a MySQL table. Naturally, if you’re like me, it’s probable that you want to see an example that shows how to use this class. However, this example will be created in the final article, so now that you’ve been warned, you don’t have any excuses to miss it!