日韩天天综合网_野战两个奶头被亲到高潮_亚洲日韩欧美精品综合_av女人天堂污污污_视频一区**字幕无弹窗_国产亚洲欧美小视频_国内性爱精品在线免费视频_国产一级电影在线播放_日韩欧美内地福利_亚洲一二三不卡片区

《PHP設(shè)計模式介紹》第十四章 動態(tài)記錄模式(5)_PHP教程

編輯Tag賺U幣
教程Tag:暫無Tag,歡迎添加,賺取U幣!

推薦:《PHP設(shè)計模式介紹》第十三章 適配器模式
接口的改變,是一個需要程序員們必須(雖然很不情愿)接受和處理的普遍問題。程序提供者們修改他們的代碼;系統(tǒng)庫被修正;各種程序語言以及相關(guān)庫的發(fā)展和進(jìn)化。我孩子的無數(shù)玩具中有一個簡要地描

以下代碼實現(xiàn)上述實驗的要求。

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;
}
}

更新記錄

CRUD操作中的建立與讀取部分介紹完畢。何如更新數(shù)據(jù)呢?當(dāng)然用save()方法來更新activate record對象是合理的,但目前save()方法只能完成插入數(shù)據(jù),其代碼如下

class Bookmark{
// ...
const INSERT_SQL = “
insert into bookmark (url, name, description, tag, created, updated)
values (?, ?, ?, ?, now(), now())
“;
protected function save() {
$rs = $this->conn->execute(
self::INSERT_SQL
,array($this->url, $this->name,
$this->description, $this->tag));
if ($rs) {
$this->id = (int)$this->conn->Insert_ID();
} else {
trigger_error(‘DB Error: ‘.$this->conn->errorMsg());
}
}
}

然而,如果你已有一個有效的書簽實例,則你應(yīng)該希望看到如下代碼

class Bookmark {
// ...
const UPDATE_SQL = “
update bookmark set url = ?,
name = ?, description = ?, tag = ?,
updated = now()
where id = ?
“;
public function save() {
$this->conn->execute(
self::UPDATE_SQL
,array(
$this->url,
$this->name,
$this->description,
$this->tag,
$this->id));
}
}

要區(qū)別INSERT與UPDATE,你應(yīng)該測試書簽數(shù)據(jù)是新建的還是從數(shù)據(jù)庫中獲取得的。

首先,重新制作兩個版本的save()方法,分別命令為insert()與update()。

class Bookmark {
// ...
protected function insert() {
$rs = $this->conn->execute(
self::INSERT_SQL
,array($this->url, $this->name,
$this->description, $this->tag));
if ($rs) {
$this->id = (int)$this->conn->Insert_ID();
}
}
protected function update() {
$this->conn->execute(
self::UPDATE_SQL
,array(
$this->url,
$this->name,
$this->description,
$this->tag,
$this->id));
}
}

現(xiàn)在你新的save()方法的代碼就如下所示了。

class Bookmark {
const NEW_BOOKMARK = -1;
protected $id = Bookmark::NEW_BOOKMARK;
// ...
public function save() {
if ($this->id == Bookmark::NEW_BOOKMARK) {
$this->insert();
} else {
$this->update();
}
}
}

最后一個問題:當(dāng)你插入或是更新記錄時,時間戳總是要改變的。如果不采取從數(shù)據(jù)庫中獲取時間戳的手段,則沒有更好的方法在書簽對象中記錄準(zhǔn)確的時間戳了。因為在插入與修改中都要應(yīng)用到,所以要更改Activate Record類,當(dāng)save()方法完成后,就更新時間戳(實例的相關(guān)屬性值),以避免后來產(chǎn)生的不同步。

分享:《PHP設(shè)計模式介紹》第十二章 裝飾器模式
若你從事過面向?qū)ο蟮膒hp開發(fā),即使很短的時間或者僅僅通過本書了解了一些,你會知道,你可以 通過繼承改變或者增加一個類的功能,這是所有面向?qū)ο笳Z言的一個基本特性。如果已經(jīng)存在的一個php

來源:模板無憂//所屬分類:PHP教程/更新時間:2008-08-22
相關(guān)PHP教程