项目和新需求:
我们有一个PHP写的webmail系统,有一个mail_list.php用于展现用户的邮件列表这个页面支持folderId参数(因为邮件是存在不同的文件夹下的)由于邮件太多所以支持翻页。现在需要在系统里增加标签。细化下来:需要在原有的邮件列表里增加标签列,和支持tagid检索出一个邮件列表(列表里也增加标签列)
代码和新需求mail_list.php调用GetMailList函数,这个函数传入文件夹ID,页码,页大小,得到HTML TABLE和导航链接GetMailList用T_Page类得到请求的一页数据再处理为HTML表格虽然T_Page只支持单表查询,但是在整个系统里还是被广泛使用因为动T_Page还是有风险的,所以最好继承它,然后让需要多表查询的地方直接实例化子类
重构前
/*功能:查询指定文件夹下的特定页的邮件列表(HTML Table)*/function GetMailList($folderId, $pageNo, $pageSize){ global $db_obj, $pageLink, $html; // db_obj是从外部导入使用,后两个似乎要导出去 $query = " where folderId = $folderId ..."; //省略很多行 $pageclass = new T_Page; $tableName = "mail"; $condition = $query . "order by tm desc"; $pageclass->BaseSet($tableName, "id,sender,subject,content,...", $pageNo, $pageSize, $db_obj); $pageclass->SetCondition($condition); $record = $pageclass->ReadList(); // 查出来的记录集,被放到二维数组里 $pageLink=$pageclass->Page(); //存放翻页按钮的数组 $html = "
"; $html = $html . " | $subject | "; ... } $html = $html . "
重构后
class MailPage extends T_Page{ function setTotal() { ... $this->Total = $row["recordtotal"]; } function getMailList() { $Fields = $this->Field . " ,'' as taglist "; $SQL.="select $Fields from $this->Table $this->Condition"; $SQL.=" LIMIT $this->Offset , $this->MaxLine"; ... } function addTagList() { ... $tagList = Array(); for($i=0; $i < $this->Number; $i++) { $key = $this->Result[$i]["id"]; $this->Result[$i]["taglist"] = $tagList[$key]; } } //覆盖父类的接口 function ReadList() { $this->setTotal(); $this->getMailList(); $this->addTagList(); return $this->Result; } }class TagPage extends MailPage{ function SetCondition($taglist) { ... $this->Condition = sprintf(" where id in (%s) order by tm desc ", $mailList); }}