PHP OOP实践

时间:2014-10-21 16:58:21

标签: php oop

如果我想检索单个记录,我认为下面给出的代码工作正常(我正忙于学习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;
    }
}   

1 个答案:

答案 0 :(得分:1)

您希望使用构造函数初始化对象的内部状态。在你的情况下,你在构造函数中做了太多,这也打破了“单一责任原则”。似乎“新闻”只是一个实体或数据传输对象,因此您必须从外部初始化它。

首先,我会保留新闻只是为了存储从数据库收到的信息。

其次,我将在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);