Using Different Target Files for Persistent Objects

Persistent objects appear at first to be an obscure and hard-to-grasp subject that belongs under software development. In fact, persistent objects are simply regular objects spawned from a class that has some form of storage mechanism associated with it. This six-part series shows you how to get the most out of persistent objects in your web applications.

In the particular case of PHP 5, which as you know is well-suited for building web applications, persistent objects are very often created to overcome the stateless nature of the HTTP protocol. This implies defining classes that are capable of saving the state of their instances to a database table, a text file or a plain cookie. (Keep in mind, though, that this last option is considered to be a pretty unsafe solution because it relies heavily on the client’s environment to work properly).

Naturally, if you’ve been a patient reader and had the chance to read all of the previous articles in this series, then by now building persistent objects in PHP 5 should be familiar to you. In those articles I’ve used a decent number of code samples to help explain how to create these objects. My first examples showed how to do it with a few cookies; later, I demonstrated the technique using a predefined text file.

More specifically speaking, in the last article I defined a simple class that could save the properties assigned to its instances to a unique file called “data.txt.” While this example class could be considered a genuine persistent entity, I have to admit that in its current state, it lacks some flexibility. After all, it can only store its properties in a single text file, which is not too useful. 

To address this limitation, in this fourth part of the series I’m going to tweak the definition of the class created in the previous article. The modification will allow it to save its properties to different text files, thus considerably enhancing its functionality. 

Are you ready to learn more about building persistent objects with PHP 5? Then  start reading now!

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

If you still haven’t read the previous installment of this series, where I explained how to build a basic class that could save its properties to a predefined text file, don’t worry. Below I’ve included this class’s complete definition, along with a short script that demonstrates how to use it.

Here’s the full source code of this persistent class, so pay attention to it:

class User

{

private $data = array();

private $file = ‘data.txt’;

 

// constructor

public function __construct()

{

list($this->data['name'], $this->data['email']) = explode(‘|’, file_get_contents($this->file));

 }

 

// set undeclared property

public function __set($property, $value)

{

if ($property !== ‘name’ and $property !== ‘email’)

{

return;

}

$this->data[$property] = $value;

}

 

// get undeclared property

public function __get($property)

{

if (isset($this->data[$property]) === TRUE)

{

return $this->data[$property];

}

}

 

// save object to session variable

public function __destruct()

{

file_put_contents($this->file, $this->name . ‘|’ . $this->email);

 }

}

Definitely, the above code fragment demonstrates how simple it is to build a class that can save the properties of its instances to a specific file, in this particular case called “data.txt.” Of course, the implementation of its destructor makes the whole saving process really simple. It’s performed transparently when the PHP interpreter invokes this method before it finishes executing the calling script.

And now that you grasped the logic driving the previous class, here’s a script that populates the properties of a user object with some trivial values, and then stores them in the specified text file:

// example on using a persistent object with a text file

$user = new User();

$user->name = ‘Mary’;

$user->email = ‘mary@mydomain.com’;

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

Once the properties have been properly saved to the “data.txt” file, it’s possible to retrieve them on a different web page, as shown below, if the definition of the class has been previously included. Take a look:

// assign new values to properties of the persistent object

$user = new User();

$user->name = ‘Susan’;

$user->email = ‘susan@domain.com’;

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

There you have it. As you can see, creating persistent objects in PHP 5 is much easier than you might think, right? However, in keeping with the concepts described in the introduction, it’s feasible to make the example “User” class a bit more flexible by providing it with the ability to save its instances to a text file other than the default “data.txt.”

But how can this be done in a few easy steps? Well, the upgrade process would be as simple as refactoring the class’s constructor. The constructor needs to be able to take, as an input argument, the name of the file that will be used for storing the corresponding properties.

The full details of this process will be discussed in detail in the section to come. To learn more, read the following segment.

{mospagebreak title=Saving class properties to different text files} 

As I said in the previous section, it’d be desirable to extend the functionality of the example “User” class by making it able to save its properties to a different text file. This can be achieved in several ways, but in this case I’m simply going to redefine the class’s constructor, as shown below:

class User

{

private $data = array();

private $file = ‘data.txt’;

 

// constructor

public function __construct($file = ”)

{

if ($file != ”)

{

$this->file = $file;

}

list($this->data['name'], $this->data['email']) = explode(‘|’, file_get_contents($this->file));

}

 

// set undeclared property

public function __set($property, $value)

{

if ($property !== ‘name’ and $property !== ‘email’)

{

return;

}

$this->data[$property] = $value;

}

 

// get undeclared property

public function __get($property)

{

if (isset($this->data[$property]) === TRUE)

{

return $this->data[$property];

}

}

 

// save object to session variable

public function __destruct()

{

file_put_contents($this->file, $this->name . ‘|’ . $this->email);

}

}

As you can see above, now the constructor of the “User” class has been slightly modified to accept as an incoming argument the name of the file that will be used to store the corresponding properties. This subtle change definitely permits much more more flexibility when creating a persistent object.

To understand this concept more clearly, I suggest that you look at the following code sample. It will first spawn a new user object, and then assign some basic properties dynamically; finally, it will save those properties to a different text file, this time called “newfile.txt.” Here’s the example:

// 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

Undeniably, the previous code fragment is very easy to follow, so I won’t bore you by explaining once again how it works. It’s valid to note here, though, how a small change introduced into the originating class of this persistent object can have a considerable impact on its functionality. Pretty good, right?

At this point, naturally the properties of the previous user object have been neatly saved to the target “newfile.txt” file, but this is only the half of the story. It’s necessary to show how those properties can be retrieved in a different file, thus proving that they’re capable of persisting across different HTTP requests.

With that goal in mind, in the last section of this tutorial I’m going to code another short script, which will illustrate the full details of this retrieval process.

Now, click on the link that appears below and read the final segment. We’re almost finished!

{mospagebreak title=Restoring the persistent object on a different web page}

As I said in the earlier segment, I’d like to finish this tutorial by showing you how to restore the properties of the user object created previously, and how to assign new values to them as well.

The PHP file responsible for performing the restoration process would look like this:

<?php

 

class User

{

private $data = array();

private $file = ‘data.txt’;

 

// constructor

public function __construct($file = ”)

{

if ($file != ”)

{

$this->file = $file;

}

list($this->data['name'], $this->data['email']) = explode(‘|’, file_get_contents($this->file));

}

 

// set undeclared property

public function __set($property, $value)

{

if ($property !== ‘name’ and $property !== ‘email’)

{

return;

}

$this->data[$property] = $value;

}

 

// get undeclared property

public function __get($property)

{

if (isset($this->data[$property]) === TRUE)

{

return $this->data[$property];

}

}

 

// save object to session variable

public function __destruct()

{

file_put_contents($this->file, $this->name . ‘|’ . $this->email);

}

}

 

// assign new properties to the persistent object

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

$user->name = ‘John’;

$user->email = ‘john@domain.com’;

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

?>

Apart from including the definition corresponding to the “User” class, only three lines of code are required to retrieve the properties of its derived $user object. For example purposes, I decided to populate the properties with new values, but as you may have guessed it’s possible keep the original values and use them afterward for further manipulation.

With this last example I’m finishing this article. As usual, feel free to edit all of the code samples shown in this tutorial to arm yourself with a more solid background in creating persistent objects with PHP 5.

Final thoughts

That’s it for the moment. In this fourth chapter of the series, I discussed how to define a persistent class in PHP 5, which could save its properties to a specified text file passed previously as an input argument to the constructor. Indeed, the process was very straightforward, so in theory you shouldn’t have major problems creating a class like this on your own.

Moving forward, it’s time to talk about the topics that I plan to cover in the next article. Considering that MySQL is the most popular RDBMS associated with PHP 5, in that tutorial I’m going to explain how to create persistent objects that can store their properties in a MySQL database table.

My last piece of advice is simple: don’t miss the upcoming part!

[gp-comments width="770" linklove="off" ]
antalya escort bayan antalya escort bayan