使用db的结果填充对象

时间:2014-12-12 18:58:06

标签: php oop pdo

让我们说我们有这个课程:

class Cup {
    public $color;
    public $material;

    public function getMyCupById($id){
        //prepare statement
        $query = $db->prepare('SELECT * FROM cups WHER cup_id=?');
        $query->bindValue(1,$id);
        $query->execute();

        $cup = $pages->fetch(PDO::FETCH_OBJ);

        // The "problem" is from here
        $this->color = $cup->color;
        $this->material = $cup->material;
        // To here
    }
}

那么,这是否是#34;填充"来自DB的对象还是有更优雅的方法来做到这一点?

最后,执行代码将是:

$cup = new Cup;

//other lines of code

$cup->getMyCupById($id);

1 个答案:

答案 0 :(得分:2)

您可以将其定义为:

,而不是在Cup类中包含数据库交互
class Cup {
    public $color;
    public $material;
}

并有一个单独的数据访问类来处理数据库交互。

class CupDataAccess {
    private $db;

    public function __construct(PDO $db) {
        $this->db = $db;
    }

    public function getMyCupById($id) {
        $sql = 'SELECT color, material FROM cups WHERE cup_id=?'
        $query = $this->db->prepare($sql);
        $query->bindValue(1, $id);
        $query->execute();
        return $query->fetchObject('Cup');
        // Using fetchObject this way will automatically associate column
        // names from the fetched row with corresponding property names of
        // the specified class.            
    }    
}

所以你可以用

制作杯子
$cupDataAccess = new CupDataAccess($pdo);
$cup = $cupDataAccess->getMyCupById(1);