[英]PHP OOP practice
我想下面給出的代碼可以正常工作(我正忙於學習OOP PHP,但尚未測試這些代碼),如果我想檢索單個記錄。 如果我要循環播放記錄怎么辦? 怎么做 ? 我可以使用單一類檢索單一和循環記錄嗎? 如果是,怎么辦?
include('class.database.php');
class News
{
protected $id;
protected $title;
protected $detail;
protected $updatedon;
protected $views;
protected $pic;
protected $cat;
protected $reporter;
function __construct ($id);
$newsdb = new Database;
$Query = "SELECT * FROM news WHERE nws_sn =".$id;
$db->query($Query);
$db->singleRecord();
$this->id = $newsdb->Record['nws_sn'];
$this->title = $newsdb->Record['nws_title'];
$this->detail = $newsdb->Record['nws_detail'];
$this->updatedon = $newsdb->Record['nws_time'];
$this->views = $newsdb->Record['nws_view'];
$this->pic = $newsdb->Record['nws_pic'];
$this->cat = $newsdb->Record['nws_cat_id'];
$this->reporter = $newsdb->Record['nws_rptr_id']
}
function getId () {
return $this->id;
}
function getTitle () {
return $this->title;
}
function getDetail () {
return $this->detail;
}
function getViews () {
return $this->views;
}
function getImage () {
return $this->pic;
}
function getTime () {
return $this->updatedon;
}
}
您想使用構造函數來初始化對象的內部狀態。 在您的情況下,您在構造函數中做了太多事情,這也違反了“單一責任原則”。 似乎“新聞”只是一個實體或數據傳輸對象,因此您必須從外部對其進行初始化。
首先,我將保留新聞只是為了存儲從數據庫接收到的信息。
其次,我將在News類中創建一個靜態工廠方法,以便它創建一個實際的News對象,並使用從外部傳遞給該方法的數據填充該對象。 另外,您可以創建一個工廠對象來創建您的實體,但是由於構造邏輯非常簡單,因此我認為將其保留在單個方法中是有意義的。
考慮下面的代碼:
class News
{
protected $id;
protected $title;
protected $detail;
protected $updatedon;
protected $views;
protected $pic;
protected $cat;
protected $reporter;
public static createFromRecord($record)
{
$obj = new self();
$obj->setId($record->Record['nws_sn']);
$obj->setTitle($record->Record['nws_title']);
$obj->setDetail($record->Record['nws_detail']);
$obj->setUpdateon($record->Record['nws_time']);
$obj->setViews($record->Record['nws_view']);
$obj->setPic($record->Record['nws_pic']);
$obj->setCat($record->Record['nws_cat_id']);
$obj->setReporter($record->Record['nws_rptr_id']);
return $obj;
}
function getId () {
return $this->id;
}
function getTitle () {
return $this->title;
}
function getDetail () {
return $this->detail;
}
function getViews () {
return $this->views;
}
function getImage () {
return $this->pic;
}
function getTime () {
return $this->updatedon;
}
// ... add public setters for the properties
}
...
$newsdb = new Database;
$Query = "SELECT * FROM news WHERE nws_sn =".$id;
$db->query($Query);
$record = $db->singleRecord();
$newsObject = News::createFromRecord($record);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.