HomePHP Page 2 - The Active Record Pattern, concluded
Active Record Instance ID - PHP
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).
In the previous example, most of the attributes are public; however, the ID of the bookmark is protected to avoid accidents changing its value (this would be problematic when you wanted to later update the bookmark). Since $id is protected, add an accessor method to retrieve it from the Bookmark.
class Bookmark { protected $id; //... public function getId() { return $this->id; } }
How do you test this?
class ActiveRecordTestCase extends UnitTestCase { // ... function testGetId() { $this->add(‘http://php.net’, ‘PHP’, ‘PHP Language Homepage’, ‘php’); // second bookmark, id=2 $link = $this->add(‘http://phparch.com’, ‘php|architect’, ‘php|arch site’, ‘php’); $this->assertEqual(2, $link->getId()); } }
Immediately above, add() persists several bookmarks and verifies that the latter of the two matches.
So far, so good, but what if you want to verify the database entry based on a different criteria than the bookmark ID? How can you make sure the correct ID from the database is being returned? A good technique is to SELECT from the database using a known attribute and verify the ID from the returned row. Here’s a test using this methodology:
class ActiveRecordTestCase extends UnitTestCase { // ... function testGetId() { $this->add(‘http://php.net’, ‘PHP’, ‘PHP Language Homepage’, ‘php’); // second bookmark, id=2 $link = $this->add(‘http://phparch.com’, ‘php|architect’, ‘php|arch site’, ‘php’); $this->assertEqual(2, $link->getId()); $alt_test = $this->conn->getOne( “select id from bookmark where url = ‘http://phparch.com’”); $this->assertEqual(2, $alt_test); //alternatively $this->assertEqual($link->getId(), $alt_test); } }
Notice that this test resembles the SQL you might execute manually to verify the insertion of the data into the bookmark table. By coding this as a test, rather than simply performing it once by hand, you can continue to verify it is taking place each time you run the tests.