PHP Objects, Patterns and Practice (3rd edition)

(Barry) #1

C H A P T E R 13


■ ■ ■


Database Patterns


Most web applications of any complexity handle persistence to a greater or lesser extent. Shops must
recall their products and their customer records. Games must remember their players and the state of
play. Social networking sites must keep track of your 238 friends and your unaccountable liking for boy-
bands of the ’80s and ’90s. Whatever the application, the chances are it’s keeping score behind the
scenes. In this chapter, I look at some patterns that can help.
This chapter will cover



  • The Data Layer interface: Patterns that define the points of contact between the
    storage layer and the rest of the system

  • Object watching: Keeping track of objects, avoiding duplicates, automating save
    and insert operations

  • Flexible queries: Allowing your client coders to construct queries without thinking
    about the underlying database

  • Creating lists of found objects: Building iterable collections

  • Managing your database components: The welcome return of the Abstract Factory
    pattern


The Data Layer


In discussions with clients, it’s usually the presentation layer that dominates. Fonts, colors, and ease of
use are the primary topics of conversation. Amongst developers it is often the database that looms large.
It’s not the database itself that concerns us; we can trust that to do its job unless we’re very unlucky. No,
it’s the mechanisms we use to translate the rows and columns of a database table into data structures
that cause the problems. In this chapter, I look at code that can help with this process.
Not everything presented here sits in the Data layer itself. Rather I have grouped some of the
patterns that help to solve persistence problems. All of these patterns are described by one or more of
Clifton Nock, Martin Fowler, and Alur et al.


Data Mapper


If you thought I glossed over the issue of saving and retrieving Venue objects from the database in the
“Domain Model” section of Chapter 12, here is where you might find at least some answers. The Data
Mapper pattern is described by both Alur et al in Core J2EE Patterns (as Data Access Object) and Martin
Fowler in Patterns of Enterprise Application Architecture (in fact, Data Access Object is not an exact

Free download pdf