PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1
CHAPTER 12 ■ ENTERPRISE PATTERNS

When you need to put your system through its paces, you can use test mode to switch in a fake
registry. This can serve up stubs (objects that fake a real environment for testing purposes) or mocks
(similar objects that also analyze calls made to them and assess them for correctness).


Registry::testMode();
$mockreg = Registry::instance();


You can read more about mock and stub objects in Chapter 18, “Testing with PHPUnit.”

Registry, Scope, and PHP


The term scope is often used to describe the visibility of an object or value in the context of code
structures. The lifetime of a variable can also be measured over time. There are three levels of scope you
might consider in this sense. The standard is the period covered by an HTTP request.
PHP also provides built-in support for session variables. These are serialized and saved to the file
system or the database at the end of a request, and then restored at the start of the next. A session ID
stored in a cookie or passed around in query strings is used to keep track of the session owner. Because
of this, you can think of some variables having session scope. You can take advantage of this by storing
some objects between requests, saving a trip to the database. Clearly, you need to be careful that you
don’t end up with multiple versions of the same object, so you may need to consider a locking strategy
when you check an object that also exists in a database into a session.
In other languages, notably Java and Perl (running on the ModPerl Apache module), there is the
concept of application scope. Variables that occupy this space are available across all instances of the
application. This is fairly alien to PHP, but in larger applications, it is very useful to have access to an
applicationwide space for accessing configuration variables. You can build a registry class that emulates
application scope, though you must be aware of some pretty considerable caveats.
Figure 12–3 shows a possible structure for Registry classes that work on the three levels I have
described.


Figure 12–3. Implementing registry classes for different scopes

Free download pdf