sledgehammer / orm
Sledgehammer ORM模块:对象关系映射
22.07.0
2022-08-07 08:15 UTC
Requires
- sledgehammer/core: >=18
README
Sledgehammer框架的对象关系映射(ORM)模块。
功能
- 完整自动补全支持
- POCO支持。仓库可以加载普通的旧类对象(POCO)
- 从数据库检测关系
- 可选的ActiveRecord前端
- Linq风格筛选支持
- 支持复杂的属性映射。一列"city"可以被映射到属性"address->city"
- 1个数据库记录映射到1个实例。通过IdentityMap
- 关系是对象,要设置"customer_id",你需要将"customer"属性设置为顾客对象。
- 级联保存(). 保存将更新和插入所有相关记录。
- 支持多个后端:PDO(MySQL,SQLite),Webservices(Twitter等)
- 干净的查询。(没有"1 = 1"的WHERE语句等)
用法
use Sledgehammer\Orm\Repository; // inside your bootstrap.php $repo = Repository::instance(); $repo->registerBackend(new DatabaseRepositoryBackend("default")); // Extract models from the "default" database connection. // Somewhere in your application $repo = Repository::instance(); $customer = $repo->getCustomer($_GET['id']); $customer->name = $_POST['name']; $repo->saveCustomer($customer); // When the Customer class extends Sledgehammer\ActiveRecord the familiar API is also available $customer = Customer::one($_GET['id']); $customer->name = $_POST['name']; $customer->save(); // Linq style filtering $selection = $repo->allCustomers()->where(array('name' => 'James Bond'))->where(function ($c) { return $c->isSpecialAgent(); }); $list = Customer::all()->select('name', 'id'); // Results in: array($id1 => $name1, $id2 => $name2, ...)
关系和占位符
对象的关联通过占位符类按需加载。只需使用对象,就像所有关联已经加载一样
$customer->orders[0]->product->title;
一直工作并提供自动补全。
占位符技术的缺点是
if ($customer->orders[0]->id === $order->id) { ... } // Always works
if ($customer->orders[0] === $order) { ...} // WRONG. Doesn't work reliably
这是因为$order可能仍然是一个BelongsToHolder对象,在使用时将被替换(调用函数,获取或设置属性)旁注:BelongsToHolder通常知道id值,读取$order->id不会触发替换/查询。
更新关系
你不会在对象中找到任何"customer_id"属性,要更改"customer_id",你需要使用顾客对象。
$order->customer = $repo->getCustomer(1);
$repo->saveOrder($order);
不要这样做
$order->customer->id = 1; // WRONG
$repo->saveOrder($order); // Throws Exception
这是因为你正在更改顾客对象,而仓库在尝试保存订单之前不允许订单和id更改。
字典
后端:数据检索和存储机制。模型:将后端数据映射到实例的配置。实例:根据模型从后端数据创建的对象。