caseyamcl / mongorecord
原始 MongoRecord 库的定制克隆(https://github.com/lunaru/MongoRecord)
Requires
- php: >=5.3.0
This package is auto-updated.
Last update: 2019-04-11 18:06:31 UTC
README
MongoActiveRecord 是一个基于 PHP 的 Mongo Active Record 模式 ORM 层,构建在 PHP Mongo PECL 扩展 之上
MongoActiveRecord 是 “MongoRecord 工具” 的分支,该工具的链接为 http://github.com/###/MongoRecord,它是由在线分类广告网站 Oodle 提取出来的。Oodle 对一个可管理的、易于理解的接口处理超可扩展的 Mongo 数据存储的需求是 MongoRecord 的主要原因。它是为了与 PHP 应用程序一起使用而开发的,这些应用程序希望通过一个良好的抽象层来处理 Mongo 的扩展能力。
这个分支与原始版本的不同之处在于,它要求你明确声明对象的属性。这允许你定义应用程序中的数据结构,并且只需查看你的 MongoRecord 类的源代码,就可以轻松地看到每个集合中每条记录包含的属性。
特性
- 集合名称按约定命名
- 属性按约定命名
- 验证
- 回调
- 排序、偏移量、限制
要求
- PHP 5.3+
- Mongo PECL
安装
将源文件提取到你的 PHP 库路径中的一个目录。
用法
基础
使用 MongoRecord 的方法很简单,只需声明扩展基本 ORM 类的类,并添加你希望拥有的属性的 private
或 protected
属性。
class Person extends BaseMongoRecord { protected $firstName;
protected $lastName; }
// initialize connection and database name BaseMongoRecord::$connection = new Mongo(); BaseMongoRecord::$database = 'myapp';
这为 Person
提供了基本的 CRUD 方法:save()
、destroy()
、findOne()
和 find()
。
每个类都自动按约定映射到 Mongo 集合。
例如。Person
→ people
MyClass
→ my_classes
可以为子类手动设置集合名称。
你可以通过覆盖类名来实现,如下面的示例所示。
class PersonClassNameIsTooComplicated extends BaseMongoRecord { protected static $collectionName = 'person'; }
创建和检索
可以通过实例化和保存来创建新记录
$person = new Person(); $person->save(); // true or false depending on success
$person = Person::findOne(); $person->destroy();
你还可以添加你想要查找的选项。
// find the first Person sorted by name, starting from the tenth Person::find(array(), array('sort' => array('name' => 1), 'offset' => 10, 'limit' => 1));
属性
属性可以通过几种不同的方式设置
在构造函数上批量设置
$person = new Person(array('name' => 'Bob', 'description' => 'foobar'));
One-by-One:
pre.. $person->age = 25; $pseron->gender = 'Male';
Chained:
pre.. $person->setAge(25)->setGender("Male"); $person->save(); // returns true or false Person::find(array('name' => 'Bob', 'gender' => 'Male')); // finds all male Bobs in the people collection.
验证
可以根据属性的名称添加验证
class Person extends BaseMongoRecord { public function validatesName($name) { if ($name == 'Bob') return false; else return true; } }
$person = new Person(); $person->setName("Bob"); $person->save(); // fails!
回调
可以为以下事件添加回调
- beforeSave()
- afterSave()
- beforeValidation()
- afterValidation()
- beforeDestroy()
- afterNew()
在一个新的保存、销毁周期中,验证按照以下顺序被调用
afterNew -> beforeValidation -> afterValidation -> beforeSave -> afterSave -> beforeDestroy
class Person extends BaseMongoRecord { public function beforeSave() { if ($this->getName() == 'Bob') $this->setName('Bill'); } }
1.x 和 2.x 版本的 MongoRecord 之间的差异
在 2.x 版本中,find()
方法是懒加载的,并返回一个 MongoRecordIterator
而不是 MongoRecord
。迭代器可以像 数组
一样处理,并实现了 PHP 的 Iterator
和 Countable
接口。
因此,2.x 版本与 1.x 版本 不兼容,因为 find()
的结果可能无法保证表现一致。(例如,在 2.× 版本中,$results[3] 不与 @find()
一起使用。)你可以使用 findAll()
代替,它在 1.× 版本中的行为与 find()
相同。
致谢
感谢 Rasmus 对懒加载查找的建议。