php 抽象類的簡單應用
更新時間:2011年09月06日 23:22:07 作者:
我想博客中的 文章列表和單個的文章閱讀 統(tǒng)一起來,我覺得除了sql查詢語句結構不同,HTML代碼不同,其它也就一樣。不過話說回來,這兩個都是主要功能,所以這的確有點不適合,不過昨晚讀了一點設計模式,好歹得寫點啥好。
All right, 父類postParent定義為抽象,規(guī)定子類必須重新實現(xiàn) buildHTML()方法,這個方法并沒有花括號,如果有不管有沒有內容都會報錯的。
現(xiàn)在越看越覺得這代碼完全沒必要用抽象類,用繼承也都很雞肋,好吧,也沒啥好說的好像。。。。。
另外我把mysql 分開在外面了,所以調用方法很麻煩
1,先實例化 readArticle
2,mysql查詢,參數(shù)來自 readArticle::getSQL();
3,返回mysql結果資源給 readArticle::fetchResult( $result );
4,readArticle::buildHTML(); 返回HTML
如果是列表循環(huán)輸出的話,把 3 和 4 重復調用就可以了
abstract class postParent
{
protected $querySQL;
public $fetchResult;
public $timeAgo; // eg : 2 days ago
abstract protected function buildHTML();
public function getSQL()
{
return $this->querySQL;
}
public function fetchResult( $result )
{
$this->fetchResult = mysql_fetch_assoc( $result );
}
public function error()
{}
}
class readArticle extends postParent
{
public function __construct( $id )
{
$this->querySQL =<<<eof
SELECT title, author, text, unixtime FROM post
WHERE id = $id ORDER BY unixtime DESC;
eof;
}
public function buildHTML()
{
return <<<eof
<div id="post-text">
<div class="post-title-div">
<h4>
<a
class="post-title-a" > {$this->fetchResult['title']}
</a>
</h4>
</div>
<div class="post-info-div">
<span class='post-info-author'>{$this->fetchResult['author']}</span> at
<time class='post-info-time'>{$this->timeAgo}</time>
</div>
<div class="post-p-div">
{$this->fetchResult['text']}
</div>
</div>
eof;
}
}
現(xiàn)在越看越覺得這代碼完全沒必要用抽象類,用繼承也都很雞肋,好吧,也沒啥好說的好像。。。。。
另外我把mysql 分開在外面了,所以調用方法很麻煩
1,先實例化 readArticle
2,mysql查詢,參數(shù)來自 readArticle::getSQL();
3,返回mysql結果資源給 readArticle::fetchResult( $result );
4,readArticle::buildHTML(); 返回HTML
如果是列表循環(huán)輸出的話,把 3 和 4 重復調用就可以了
復制代碼 代碼如下:
abstract class postParent
{
protected $querySQL;
public $fetchResult;
public $timeAgo; // eg : 2 days ago
abstract protected function buildHTML();
public function getSQL()
{
return $this->querySQL;
}
public function fetchResult( $result )
{
$this->fetchResult = mysql_fetch_assoc( $result );
}
public function error()
{}
}
class readArticle extends postParent
{
public function __construct( $id )
{
$this->querySQL =<<<eof
SELECT title, author, text, unixtime FROM post
WHERE id = $id ORDER BY unixtime DESC;
eof;
}
public function buildHTML()
{
return <<<eof
<div id="post-text">
<div class="post-title-div">
<h4>
<a
class="post-title-a" > {$this->fetchResult['title']}
</a>
</h4>
</div>
<div class="post-info-div">
<span class='post-info-author'>{$this->fetchResult['author']}</span> at
<time class='post-info-time'>{$this->timeAgo}</time>
</div>
<div class="post-p-div">
{$this->fetchResult['text']}
</div>
</div>
eof;
}
}
您可能感興趣的文章:
相關文章
php中sprintf與printf函數(shù)用法區(qū)別解析
這篇文章主要介紹了php中sprintf與printf函數(shù)用法區(qū)別解析,需要的朋友可以參考下2014-02-02屏蔽機器人從你的網(wǎng)站搜取email地址的php代碼
屏蔽機器人從你的網(wǎng)站搜取email地址然后發(fā)垃圾郵件的處理方法,需要的朋友可以參考下2012-11-11