創建ImagesStore
基類:
class ImagesStore
{
// See comments about accessors below.
private $table;
private $id_column;
public function insertImage($id, $pid) {
try {
$values = array($id, $pid);
$table = $this->getTable();
$id_column = $this->getIdColumn();
$sth = $this->dbh->prepare("INSERT INTO {$table} ($id_column, pid) VALUES (?, ?)");
if ($sth->execute($values)) {
return true;
}
}
catch (PDOException $e) {
$this->errorLogger($e);
}
}
protected function __construct($table, $id_column) {
$this->table = $table;
$this->id_column = $id_column;
}
// These accessors are only required if derived classes need access
// to $table and $id_column. Declaring the fields "private" and providing
// "protected" getters like this prevents the derived classes from
// modifying these values which might be a desirable property of these
// fields.
protected function getTable() {return $this->table;}
protected function getIdColumn() {return $this->id_column;}
// More implementation here...
// Initialize $dbh to something etc.
// Provide "errorLogger" method etc.
}
,創造DreamsImagesStore
和InterestsImagesStore
專業:
class DreamsImagesStore extends ImagesStore {
public function __construct() {
parent::__construct('dreams_images', 'dream_id');
}
}
class InterestsImagesStore extends ImagesStore {
public function __construct() {
parent::__construct('interests_images', 'interest_id');
}
}
最初的方法insertNewDreamImage
可以被重命名爲insertImage
因爲它實際上是比原來更普遍名字暗示。
請注意,ImagesStore
也可以聲明爲abstract
如果您想阻止它的直接實例化。
可以採用另一種方法是不從ImagesStore
都懶得派生類,只是通過使__construct
方法public
並調用它,如下所示實例化它直接:
$dreamsImagesStore = new ImagesStore("dreams_images", "dream_id");
另一種方法也可能是在ImagesStore
中實施靜態工廠方法。
+1用於識別何時需要幫助*在創建需要由其他人重構的雜亂混亂之前 – Zak 2010-10-04 21:42:27
@Zak謝謝。我嘗試編碼,就像跟在我後面的人是一個殺人狂。當我無法理解大部分正在說的模式書時,我想到一個真實有意義的例子可以幫助我將自己的思想包圍起來。 – 2010-10-04 21:52:42