hamboldt / silk-orm
zend-db 对象关系映射器
Requires
- easyframework/collections: >=v4.0.0
- hamboldt/php-doc-reader: dev-master
- zendframework/zend-db: >=2.5.1
- zendframework/zend-eventmanager: >=2.5.2
This package is not auto-updated.
Last update: 2024-09-18 10:13:54 UTC
README
O ORM Silk (英文名为 Silk) 是一个集成于 Zend Framework 2 结构的集成对象映射系统,旨在易于使用、轻量级和易于配置。它允许将表转换为对象,然后使用 Zend 的 SQL 查询标准访问数据。换句话说,它的作用是在数组级别映射您的对象。其余的都由 Zend 处理 - 与数据库进行数组事务。
composer require hamboldt/silk-orm
如何工作
配置
类
@configure {"table":"table_name"}
- 指定对象在数据库中的表。@configure {"primary_key":"idtable"}
- 指定表的键。
属性
@configure {"ignore":true}
- 在构建查询时忽略对象属性。@configure {"ignoreIfNull":true}
- 仅在属性为空时忽略对象属性。@configure {"alias":"somecolumn"}
- 指定属性在表中的列名。@configure {"type":"\\Garage\\Car"}
- 自动实例化可映射的对象。
如何使用
实例化
以下示例说明了如何实例化单个对象。可以使用 Zend 的 where 子句,就像在 TableGateways 中使用一样,因为 Silk 使用 ZF2 的 TableGateway 构建结果。
$user = new User(1); // pelo valor da chave primária $user = new User(["name"=>"lucas"]); // por um where com array $user = new User(function(Select $select){ /* ... */ }); // Pelo select do zf2
多选
以下示例说明了如何实例化多个对象。为了存储对象集合,我们使用 easyframework/collections 库。
$collection = User::select(["name"=>"lucas"]); $collection = User::select(function(Select $select){ /* ... */ }); $collection->map(function(User $user){ echo $user->getCompany()->getName() . "\n"; });
插入新记录
当对象被实例化且构造函数没有传递任何参数时,它会创建一个空对象,也就是说,它没有任何值,也没有为它定义任何 id。当对象的 id 为空($company->getId() == null
)时,调用 save() 方法将在数据库中插入新记录。如果它已经有一个定义的 id,则将更新记录。
$company = new Company(); $company->setName("Softwerk"); $company->save(); echo $company->getId(); // 1
更新记录
当对象已经有一个定义的 id,并调用 save()
方法时,将根据以下示例更新数据库中具有与对象 id 相同主键的记录。
通过主键实例化
$company = new Company(1); $company->setName("Softwerk LTDA"); $company->save();
通过显式数组实例化
$company = new Company(['idcompany' => 1]); $company->setName("Softwerk LTDA"); $company->save();
通过 ZF2 的 where 实例化
$company = new Company(function(Select $select){ $select->where->equalTo('idcompany', '1'); $select->limit(1); }); $company->setName("Softwerk LTDA"); $company->save();
更新多个记录
以下示例将更新所有列名名称为 'Softwerk' 的记录。
Company::select(['name' => 'Softwerk'])->map(function(Company $company){ $company->setName('The name has changed!'); $company->save(); });
删除记录
只有当对象的 id 已定义时,它才会被删除,就像更新操作一样。要从数据库中删除记录,只需调用对象的 delete()
方法,如下所示。
$company = new Company(1); $company->setName("Softwerk LTDA"); $company->delete();
删除多个记录
以下示例将删除所有列 name
的值为 Softwerk
的对象。
Company::select(['name' => 'Softwerk'])->map(function(Company $company){ $company->delete(); });