问题描述
使用PDO,我们现在可以以惊人的速度轻松地将字段映射到对象的属性.这个:
With PDO, we can now easily map our fields to an object's property, at a blazing speed. this:
class myClass
{}
$stmt = $db->prepare('SELECT foo,bar FROM table WHERE id=28');
$stmt->setFecthMode(PDO::FETCH_CLASS,'myClass');
$object = $stmt->fetch();
$object
现在是myClass类的对象,具有foo和bar作为属性.整洁!
$object
is now an object of class myClass with foo and bar as properties. neat!
现在,如果我可以仅使用PDO或php甚至MySQL的内置函数将对象保存回数据库中,那岂不是令人难以置信!像这样的东西:
Now, wouldn't it be incredible if I could save my object back in the database just with built-in functions from PDO or php, or even MySQL! something like this:
$stmt = $db->prepare('UPDATE table SET * = ?');
$stmt->setUpdateMode(PDO::UPDATE_CLASS);
$stmt->execute($object);
到目前为止,我为每个实例定义了自定义保存类.虽然速度很快,但维护起来很麻烦,而且容易出错.
As of now, I define custom saving classes for each instance. While fast, this is a hassle for maintaining and very error-prone.
当然,对象必须具有与其尝试更新的属性完全相同的属性,或者可以包含更少的字段,但不能更多.
Of course, an object must have exactly the same properties as what it's trying to update, or maybe less fields, but not more.
它存在吗?缺少PDO作为完美的ORM吗?!
推荐答案
所以我最终使用了oop的一个非常突出的功能:析构函数!
So I ended up using a very prominent feature of oop: destructors!
来自 http://php.net/manual/en/language.oop5 .decon.php
这很贴心,因为我想要的是在两次点击之间保持对象的状态.这意味着不同的事物,我不确定它们是否是好的做法,但这有点容易出错.
which is very sweet, because what I want is to maintain the state of my objects between clicks on my website. This implies different things which I am not sure if they are good practice or not, but it is a bit error prone.
- 数据库中的字段和对象属性应该相同,以简化析构函数代码并使其更易于移植
- 我正在使用PDO的
FETCH_CLASS
模式来构建对象(如在问题中一样)
- The fields in the database and the object properties should be the same to simplify destructor code and make it more portable
- I'm using PDO's
FETCH_CLASS
mode to build an object (as in the question)
现在有趣的部分是析构函数,它可以将属性保存回数据库中的相关字段:
now the interesting part is with the destructor, which can save back the properties to the relevant fields in the database:
function __destruct()
{
$whitelist = array_flip(array('foo','bar'));
// I'm pretty sure not all my properties belong in my table
foreach (get_object_vars($this) as $key => $value)
{
if (!isset($whitelist[$key])) continue;
$fields[] = $key . '=?';
$values[] = $value;
}
$sql = 'UPDATE table SET ' . implode($fields) . 'WHERE id=?';
$values[] = $this->getId();
$stmt = $db->prepare($sql);
$stmt->execute($values);
}
就在那里!下次我从数据库构造对象时,它与上次访问时完全相同.
and there it is! next time I construct my object from the database, it is exactly the same as it was the last time it was accessed.
这篇关于是否存在与PDO :: FETCH_CLASS相反的内容或将对象映射回数据库中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!