sbronsted / libdatabase
基于PDO的通用ORM映射器
v2.3.0
2020-09-22 13:04 UTC
Requires
- php: >=7.1
- ext-pdo: *
- sbronsted/libcommon: ^3.0
- sbronsted/libtypes: ^2.0
- sbronsted/libutil: ^2.0
Requires (Dev)
- phpunit/phpunit: ^8.5
- ruckusing/ruckusing-migrations: ^1.0
README
#Libdatabase
这是一个简单的ORM数据库映射器,提供了一些查询、创建和更新对象的便捷方法。它不支持关联。相反,我使用约定,外键是表名后追加 '_uid'。另一个约定是,对象必须有一个名为 'uid' 的属性,当您调用save并且uid == 0时,它将被转换为插入语句,否则它将被转换为更新语句。
这个库使用了php PDO库。
示例
以下定义了一个示例类
class Sample extends DbObject {
// Each object must describe the properties of the table
private static $properties = [
'uid' => Property::INT,
'case_number' => Property::CASE_NUMBER,
'date_value' => Property::DATE,
'datetime_value' => Property::TIMESTAMP,
'cpr' => Property::CPR,
'int_value' => Property::INT,
'string_value' => Property::STRING,
'decimal_value' => Property::DECIMAL,
'boolean_value' => Property::BOOLEAN
];
// A transient value which is not persisted
public $transient_value;
// mandatory method used by DbObject
public function getProperties() : array {
return self::$properties;
}
}
此类将有一个相应的表名 sample,其中属性是列。
如您所见,属性由类型描述,这意味着当对象从表行加载时,列被转换为属性类型。这样,日期就不是字符串,而是一个有意义的操作日期对象。
创建一个对象并持久化它
$sample = new Sample();
$uid = $sample->save();
查找一个或多个对象
// returns a single object
$sample = Sample::getByUid($uid);
// returns 0 or more objects
$samples = Sample::getBy(['int_value' => 1]);
更改属性并持久化它
$sample = Sample::getByUid($uid);
$sample->int_value = 1;
$sample->save();
删除一个对象
$sample = Sample::getByUid($uid);
$sample->destroy();
您还可以在DB类中访问更低级别的数据库函数,它提供了DbObject到sql的转换,或者您可以自己编写sql。
配置
这个库使用了来自 libutil 的Config类,您可以在ini文件中将数据库配置放入其中
[defaultDb]
driver=mysql
host=localhost
port=3306
name=yourDatabase
user=yourUserName
password=yourUserPassword
charset=utf8
部分名称对应于DbObject类中的静态属性$db。默认名称是'defaultDb'。