37
162
”
Elements ofObject-orientedDesign
The clear advantage of the MVC pattern is its clear-cut approach to separating
each domain of an application into a separate container. This, inturn, makes your
applications easier to maintain and to extend, particularly because you can easily
modularize each element, minimizing thepossibility ofcode duplication.
TheActiveRecord Pattern
The last patternthat we will examine isthe ActiveRecord pattern. This is used to en-
capsulate access to a data source so that the act ofaccessing its components—both
for reading and for writing—is, in fact, hidden withinthe class that implements the
pattern,allowingitscallerstoworryaboutusing thedata,as opposedtodealing with
the database.
The concept behind ActiveRecord is, therefore, quite simple, but its implemen-
tation can be very complicated, depending on the level of functionality that a class
based on this pattern is to provide. This is usually caused by the fact that, while de-
velopers tend to deal with individual database fields individually and interactively,
SQLdealswiththemaspartofrows thatmustbewrittenback tothedatabase atomi-
cally. Inaddition,thesynchronizationofdatawithinyour scripttothedatainsidethe
database can bevery challenging,because the data maychange after you’ve fetched
it fromthe databasewithout giving your code any notice.
The Standard PHP Library
The Standard PHP Library (SPL) is a great addition to PHP 5. It provides a number
of very useful facilities that expose some of PHP’s internal functionality and allow
the “userland” developer to write objects that are capable of behaving like arrays,
or thattransparently implementcertainiterative design patterns to PHP’s own core
functionality, sothat you, for example, use a
foreach()
construct to loop through an
object as if it were an array, or even access its individual elements using the array
operator
[]
.
SPL works primarily by providing a number of interfaces that can be used to im-
plement the functionality required to performcertain operations. By far, the largest
number ofpatterns exposed bySPLare iterators; they allow, among other things:
• ArrayAccess to objects