This article, the first of two parts, helps you use design patterns to better organize how your web application interacts with a database. It is excerpted from chapter 14 of the book php|architect's Guide to PHP Design Patterns, written by Jason E. Sweat (php|architect, 2005; ISBN: 0973589825).
The design patterns you've seen so far greatly improve the readability and maintainability of script internals; however, none have confronted a fundamental requirement and challenge of architecting and developing web applications: connecting to a database. This chapter and the next two chapters-Table Data Gateway and Data Mapper-provide three design patterns that better organize how your application interacts with a database.
Most web applications persist information in a database. Is there a way to abstract database connectivity to simplify table access and integrate persistence with business logic?
Conceptually, the Active Record pattern is the simplest of the database-related design patterns. The Active Record pattern embeds the knowledge of how to interact with the database directly into the class performing the interaction.
While Active Record leads to a high degree of coupling between application code and database structure, in relatively simple circumstances the issues inherent in coupling may be far easier to manage than adopting a more complex solution. Active Record is also sufficient for many first-time database projects. Only if complications arise that cannot be easily addressed with the Active Record pattern should you refactor to a Table Data Gateway (see Chapter 15), a Data Mapper (see Chapter 16), or another database design pattern.
Patterns of EnterpriseApplication Architecture
According to Martin Fowler's book, Patterns of Enterprise Application Architecture, an enterprise application is integrated with other applications, contains significant business logic (or illogical, as application requirements often reveal), and includes lots of concurrently accessed, persistent data that's accessed from a variety of interfaces. Interestingly, web applications share many of those very characteristics, which may explain why Fowler's book resonates strongly with PHP programmers.
PHP Data Objects
One project to watch is PDO. PDO is a PHP extension for high-performance database access (not database abstraction). PDO is a C-language wrapper of the native drivers and is therefore very fast. PDO provides prepared statements for all PDO drivers, enhancing the security of scripts using the library.