CHAPTER 12 ■ ENTERPRISE PATTERNS
}
}
If you intend to use a variation on this code example, make sure you check out the next section:
there are some serious issues that you should consider.
Consequences
Because both SessionRegistry and ApplicationRegistry serialize data to the file system, it is important
to restate the obvious point that objects retrieved in different requests are identical copies and not
references to the same object. This should not matter with SessionRegistry, because the same user is
accessing the object in each instance. With ApplicationRegistry, this could be a serious problem. If you
are saving data promiscuously, you could arrive at a situation where two processes conflict. Take a look
at these steps:
Process 1 retrieves an object
Process 2 retrieves an object
Process 1 alters object
Process 2 alters object
Process 1 saves object
Process 2 saves object
The changes made by Process 1 are overwritten by the save of Process 2. If you really want to create
a shared space for data, you will need to work on ApplicationRegistry to implement a locking scheme to
prevent collisions like this. Alternatively, you can treat ApplicationRegistry as a largely read-only
resource. This is the way that I use the class in examples later in this chapter. It sets data initially, and
thereafter, interactions with it are read-only. The code only calculates new values and writes them if the
storage file cannot be found. You can, therefore, force a reload of configuration data only by deleting the
storage file. You may wish to enhance the class so read-only behavior is enforced.
Another point to remember is that not every object is suitable for serialization. In particular, if you
are storing a resource of any type (a database connection handle, for example), it will not serialize. You
will have to devise strategies for disposing of the handle on serialization and reacquiring it on
unserialization.
■Note One way of managing serialization is to implement the magic methods sleep() and wakeup().
__sleep() is called automatically when an object is serialized. You can use it to perform any cleaning up before
the object is saved. It should return an array of strings representing the fields you would like to have saved. The
__wakeup() method is invoked when an object is unserialized. You can use this to resume any file or database
handles the object may have been using at the time of storage.