HomePHP Page 3 - The Active Record Pattern, concluded
Searching for Records - 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).
At the moment, a Bookmark can be stored in a database and can be (re)created by retrieving the database row that matches the bookmark’s ID. But what happens—as is usually the case—when the ID is not known or you want to search the database for a more pertinent value, such as a partial name or a URL. A common solution is to add “finder” methods.
For example, you might want a findByUrl() method to find Bookmarks similar to the parameter passed to the method. Here’s that intention expressed as a test:
class ActiveRecordTestCase extends UnitTestCase { // ... function testFindByUrl() { $this->add(‘http://blog.casey-sweat.us/’, ‘My Blog’, ‘Where I write about stuff’, ‘php’); $this->add(‘http://php.net’, ‘PHP’, ‘PHP Language Homepage’, ‘php’); $this->add(‘http://phparch.com’, ‘php|architect’, ‘php|arch site’, ‘php’); $result = Bookmark::findByUrl(‘php’); $this->assertIsA($result, ‘array’); $this->assertEqual(2, count($result)); $this->assertEqual(2, $result[0]->getId()); $this->assertEqual(‘php|architect’, $result[1]->name); } }
The test creates some data, searches for rows that contain “php” somewhere in the URL, and then verifies characteristics of the returned array of Bookmark objects. FindByUrl() is a static method, because you want Bookmark objects, but do not yet have an instance of the Bookmark class to work with. (Alternatively, you could move these “finder” methods to an object of their own, but for now the finder methods are a part of the Active Record Bookmark class.)
Here’s some code to realize the requirements expressed by the test:
class Bookmark { // ... const SELECT_BY_URL = “ select id from bookmark where url like ?”; public static function findByUrl($url) { $rs = DB::conn()->execute( self::SELECT_BY_URL ,array(“%$url%”)); $ret = array(); if ($rs) { foreach ($rs->getArray() as $row) { $ret[] = new Bookmark($row[‘id’]); } } return $ret; } }