回顾表数据网关,你应该理解findByTage()的工作原理了。
class BookmarkGateway { // ... public function findByTag($tag) { $rs = $this->conn->execute( ‘select * from bookmark where tag like ?’ ,array($tag.’%’)); return new AdoResultSetIteratorDecorator($rs); } } |
更新记录
下面,让我们来解决CRUD中的“更新”。从概念上讲,你应该让表装满数据,找到一个数据对象,改变后保存它,并且再次找到该数据并校检更改是否存储。
返回到TableDataGatewayTestCase,这儿有查找记录的代码
class TableDataGatewayTestCase extends BaseTestCase { // ... function testUpdate() { $gateway = new BookmarkGateway(DB::conn()); $this->addSeveralBookmarks($gateway); $result = $gateway->findByTag(‘php’); $bookmark = $result->current(); $this->assertIsA($bookmark, ‘ADOFetchObj’); $this->assertEqual( ‘http://blog.casey-sweat.us/’ ,$bookmark->url); $this->assertEqual( ‘PHP related thoughts’ ,$bookmark->description); } } |
并且将代码改为如下所示:
class TableDataGatewayTestCase extends BaseTestCase { // ... function testUpdate() { $gateway = new BookmarkGateway(DB::conn()); $this->addSeveralBookmarks($gateway); $result = $gateway->findByTag(‘php’); $bookmark = $result->current(); $this->assertIsA($bookmark, ‘ADOFetchObj’); $this->assertEqual( ‘http://blog.casey-sweat.us/’ ,$bookmark->url); $this->assertEqual( ‘PHP related thoughts’ ,$bookmark->description); $new_desc = ‘A change to see it is updated!’; $bookmark->description = $new_desc; $gateway->update($bookmark); } } |
改变后,重新查找该条记录并验证更新
class TableDataGatewayTestCase extends BaseTestCase { |
class BookmarkGateway{ // ... const UPDATE_SQL = ‘update bookmark set url = ? ,name = ? ,description = ? ,tag = ? ,updated = now() where id = ?’; public function update($bookmark) { $this->conn->execute( self::UPDATE_SQL ,array( $bookmark->url ,$bookmark->name ,$bookmark->description ,$bookmark->tag ,$bookmark->id )); } |
BookmarkGateway知道如何去执行SQL来更新数据,并能正确的将数据传输对象的属性的值映射到SQL语句相应的参数位置。
讨论
用表数据网关在对表进行操作,是与WEB应用中任务的执行更密切相关的。然而,表数据网关仍然与数据库表具体结构关系过于紧密(耦合)。将代码从表具体结构的依赖中独立出来将是下一章数据映射模式的主题。