This article, the second 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).
Databases usually just work, but failure is not unheard of. To make sure your code operates correctly under failure conditions, let’s simulate a failure using a Mock Object (see Chapter 6 — The Mock Object Pattern), which stands in for the connection object.
Mock::generate(‘ADOConnection’); class ActiveRecordTestCase extends UnitTestCase { //... function testDbFailure() { $conn = new MockADOConnection($this); $conn->expectOnce(‘execute’, array(‘*’,’*’)); $conn->setReturnValue(‘execute’,false); $conn->expectOnce(‘errorMsg’); $conn->setReturnValue(‘errorMsg’, ‘The database has exploded!!!!’); } }
This code calls Mock::generate() to create a MockADOConnection class, creates an instance of the mock connection, sets up some basic return values to indicate failure, and defines some expectations about what’s to be called in these circumstances.
However, because the Bookmark constructor makes a call to the static DB:conn() method to retrieve the database connection, it’s difficult to inject the mock connection into that code. There are several possible workarounds: add a method to change $this->conn, add an optional parameter to each method, or add a parameter to the constructor. Let’s opt for the latter: add an optional connection class parameter to the Bookmark constructor:
class Bookmark { // ... public function __construct($id=false, $conn=false) { $this->conn = ($conn) ? $conn : DB::conn(); // ... } }
Now new Bookmark works as normal, but new Bookmark(1, $connection) uses the $connection object instead of the normal ADOConnection object.
With that code in place, you can now easily replace the “normal” database connection object with a MockADOconnection and verify the results of a “database failure.”
class ActiveRecordTestCase extends UnitTestCase { // ... function testDbFailure() { $conn = new MockADOConnection($this); $conn->expectOnce(‘execute’, array(‘*’,’*’)); $conn->setReturnValue(‘execute’,false); $conn->expectOnce(‘errorMsg’); $conn->setReturnValue(‘errorMsg’, ‘The database has exploded!!!!’); $link = new Bookmark(1,$conn); $this->assertErrorPattern(‘/exploded/i’); $conn->tally(); }