《PHP设计模式介绍》第十五章 表数据网关模式

80酷酷网    80kuku.com

  >

前一章中使用动态记录模式对数据库表进行建立,获取,更新(通过扩展实现删除)每一行的操作。动态记录模式是一种简单的抽象数据库连接的方式,但是这种简洁性也正是它的弱点。动态记录类只处理单一的行,使得它在需要呈现大量信息的WEB应用中显得效率很低,如旅游预约,在线购物等。在这一类应用――几乎是主流的WEB应用中,数据集的使用就是更普遍更流行的。

问题

怎样才能简单的操作数据库表与表中的所有记录?

解决方案

表数据网关模式集成了动态记录模式。实际上,这个新模式的大多数代码都借签于14章动态记录模式的代码(它重用了一样的DB类与BOOKMARK TABEL DDL常量,并且也用ADOdb作为操纵数据的代码库)。然而,表数据网关模式集中于整表――记录集而不是单个的记录。

样本代码

让我们从建立操作开始,该操作完成向表中增加新记录。测试用例函数TableDataGatewayTestCase::testAdd() 完成向书签数据表中增加两条URL数据记录的步骤要求。它很大程度上参照了14章ActiveRecordTestCase::testAdd()方法,但它也其显著不同的地方,在于引入了一个新的BookmarkGateway这个表数据网关类。

class  TableDataGatewayTestCase  extends  UnitTestCase  {
function  testAdd()  {
$gateway  =  new  BookmarkGateway($conn  =  DB::conn());
$gateway->add(
‘http://simpletest.org/’,
‘SimpleTest’,
‘The  SimpleTest  homepage’,
‘testing’);
$gateway->add(
‘http://blog.casey-sweat.us/’,
‘My  Blog’,
‘Where  I  write  about  stuff’,
‘php’);
$rs  =  $this->conn->execute(‘select  *  from  bookmark’);
$this->assertEqual(2,$rs->recordCount());
$this->assertEqual(2,$conn->Insert_ID());
}
}

类似于动态记录,表数据网关测试用例示例了一个模板类,并增加一些记录到数据库。然而表数据网关模的工作对象是整张表,你只需建立一个该模式对象,并重用该对象对就能向数据表中增加更多的新记录。

这儿是BookmarkGateway一个可行的实现。

class  BookmarkGateway  {
protected  $conn;
public  function  __construct($conn)  {
$this->conn  =  $conn;
}
const  INSERT_SQL  =  “
insert  into  bookmark  (url,  name,  description, tag,  created,  updated)
values  (?,  ?,  ?,  ?,  now(),  now())
“;
public  function  add($url,  $name,  $description,  $group)  {
$rs  =  $this->conn->execute(
self::INSERT_SQL
,array($url,  $name,  $description,  $group));
if  (!$rs)  {
trigger_error(‘DB  Error:  ‘.$this->conn->errorMsg());
}
}
}

以上代码看上去很熟悉,动态记录模式与表数据网关模式的基本框架是相仿的:INSERT SQL 语句,函数参数表,对数据库错误的处理等都与动态记录模式的add()方法一次处理一条记录相类似。

建立了实现CRUD操作的代码后,现在来讨论如何获取数据。

测试用例结构

因为表数据网关的目的是处理具有多条记录的数据库表,你很有可能需要一个方便有效的方法来初始化表,使得在运行每一个实验时数据表都处于一个已知的状态。快速的解决方案是为每个实验建立一个基类,包括两个有用的方法:setup()与addSeveralBookmark,用来为每个实验重建已打乱的表和载入一些数据。

如下就是名为BaseTestCase的类

class  BaseTestCase  extends  UnitTestCase  {
protected  $conn;
function  __construct($name=’’)  {
$this->UnitTestCase($name);
$this->conn  =  DB::conn();
}
function  setup()  {
$this->conn->execute(‘drop  table  bookmark’);
$this->conn->execute(BOOKMARK_TABLE_DDL);
}
function  addSeveralBookmarks($gateway)  {
//  add(url,  name,  desc,  tag)
$gateway->add(‘http://blog.casey-sweat.us/’
,’Jason\’s  Blog’
,’PHP  related  thoughts’
,’php’);
$gateway->add(‘http://www.php.net/’
,’PHP  homepage’
,’The  main  page  for  PHP’
,’php’);
$gateway->add(‘http://slashdot.org/’
,’/.’
,’News  for  Nerds’
,’new’);
$gateway->add(‘http://google.com/’
,’Google’
,’Google  Search  Engine’
,’web’);
$gateway->add(‘http://www.phparch.com/’
,’php|architect’
,’The  home  page  of  php|architect,
an  outstanding  monthly  PHP  publication’
,’php’);
}
}

现在,每一个测试用例都源自BaseTestCase并继承它的构造器,一个setup()方法与一个addSeveralBookmarks()方法来预装一些数据。

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: