用来自 db 的结果填充对象


Fill object with result from db

假设我们有这个类:

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
    }
}

那么,这是从DB"填充"对象的正确方法,还是有更优雅的方法可以做到这一点?

最后,执行代码将是:

$cup = new Cup;
//other lines of code
$cup->getMyCupById($id);

与其在 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);