上下文
我有要插入 MySQL 数据库中的对象,因为我不想使用带有 PDO 的纯代码来完成所有数据库管理,所以我决定尝试使用 RedBean PHP ORM。
下面是我的两个对象:
class Profile {
public $Name;
public $Description;
public $Disabled;
public $ListOfProfileTranslation;
}
class ProfileTranslation {
public $LanguageCode;
public $Title;
public $Description;
}
从 Profile 的 ListOfProfileTranslation 持有一个“ProfileTranslation”数组的意义上说,上面的 2 个对象以某种方式“链接”
执行和 RedBean PHP
我知道 RedBean PHP 可以帮助简化数据库上的 CRUD 操作;我也看到了像 RedBeanPHP 这样的例子独立地声明表和每一列,但我认为如果我向它传递一个对象,RedBean PHP 可能会向我展示一些额外的魔力并自行处理它(因为表名、列名和值所以我猜 RedBean PHP 可以处理它以某种方式独立,但我可能会弄错)。
这样我就可以写这样的东西:
$Profile = R::dispense('Profile');
$Profile = $itemObject; // where $itemObject is a "Profile" object
//which already exists in memory
R::store($Profile);
我知道上面的代码会引发异常并且不会执行,但是有什么方法可以简化数据库管理吗?
或
我是否必须完成以下所有步骤:
$Profile = R::dispense('Profile');
$Profile->Name = $itemObject->Name;
$Profile->Description = $itemObject->Description;
$Profile->Disabled = $itemObject->Disabled;
R::store($Profile);
在您看来,实现这 2 个对象并将它们链接到数据库中的 RedBean PHP 的最佳解决方案是什么?
最佳答案
给定一个 $profile 和一个 $translation,你可以像这样链接它们:
$profile->ownTranslation[] = $translation;
R::store($profile);
现在 RedBeanPHP 会将翻译连接到配置文件。 至于类(class),想法是您不需要这些。假设您有这个 ProfileTranslation 类,您将如何设置属性?使用二传手?
$profTrans->setLanguageCode($lang);
那么,为什么不直接设置它们,我们都知道 setter 不会做很多有用的事情。
$profTrans->language = $lang;
如果您需要某种验证,您可以将其添加到类中,但是无需在类中重新声明属性、编写访问器等。RedBeanPHP 会自动“融合”这两者:
class Model_Translation extends RedBean_SimpleModel {
public function update() {
...validate here, just throw exception if anything is wrong...
}
}
然后...您就完成了。不需要属性声明,不需要访问器、 getter 、 setter ……就这样完成了。
这就是 RedBeanPHP 的强大之处。
干杯, 嘉宝
关于php - 使用 RedBeanPHP 在 MySQL 中插入一个对象(类出现),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18400794/