trismegiste / toolbox
如何学会停止担忧ORM,并爱上MongoDb BSON
Requires
- php: >7.4
- ext-mongodb: >1.7
- psr/log: ^1.1
- symfony/config: ^5.4|6.*
- symfony/dependency-injection: ^5.4|6.*
- symfony/form: ^5.4|6.*
- symfony/http-kernel: ^5.4|6.*
Requires (Dev)
- phpunit/phpunit: ^9.5
- symfony/console: ^5.4|6.*
- symfony/web-profiler-bundle: ^5.4|6.*
- symfony/yaml: ^5.4|6.*
README
A symfony bundle for stopping the chase after the mythical object-database, or its fake approximation a.k.a Doctrine.
MongoDb
A almost-zero-config Object Data Mapper for MongoDB. It's a micro database layer with automatic mapping that rely on BSON types. It is intended for advanced users of MongoDB who know and understand the growth of a model on a schemaless database.
When I mean "micro", I mean the sum of NCLOC is about one hundred. Therefore it is fast as hell.
安装
包含包
$ composer require trismegiste/strangelove-bundle
在清除缓存时可能会出错,因为配置文件 strangelove.yaml
还不存在。
配置包
只需运行向导并回答问题
$ vendor/bin/strangelove-wizard.php
在集合上创建存储库
创建 Trismegiste\Strangelove\MongoDb\DefaultRepository
的子类,并扩展其业务功能。
注册服务
要将存储库类 MyMovies 注册到 'movies' 集合,只需在 services.yaml
配置文件中添加
services: # ... some services App\Repository\MyMovies: $collectionName: movies
如何
由于 MongoDB 中一个文档具有原子性,因此您必须存储复杂的树形对象。如果您避免循环引用,此 ODM 将您的对象存储在 MongoDB 集合中的综合结构中。
每个对象都必须实现一个接口并使用一个特质
class MyEntity implements \MongoDB\BSON\Persistable { use \Trismegiste\Strangelove\MongoDb\PersistableImpl; }
"顶级文档"或"根文档",即拥有主键(即 MongoDB 中的字段 "_id"),必须实现 Root 接口并使用 RootImpl 特质。
class MyDocument implements \Trismegiste\Strangelove\MongoDb\Root { use \Trismegiste\Strangelove\MongoDb\RootImpl; }
存储库
有一个针对集合的默认存储库: DefaultRepository
。
加载
$record = $myRepository->load($primaryKey);
持久化
$myRepository->save($oneObjectInheritingFromRoot); $rimaryKey = $oneObjectInheritingFromRoot->getPk();
搜索
$iter = $myRepository->search(['price' => ['$ne' => null]]); foreach($iter as $record) { var_dump($record); }
此类实现了 Repository 接口。请参阅有关其的 phpdoc。
类型
- 不要在您的模型中使用 DateTime,请使用 BsonDateTime,您有一个很好的 AbstractType 来替换 Symfony DateType,该类型将 DateTime 转换为 BsonDateTime。
- 不要在您的模型中使用 SplObjectStorage,请使用 BsonObjectStorage。
- 不要在您的模型中使用 SplFixedArray,请使用 BsonFixedArray。
请阅读有关 MongoDB 中 BSON 序列化的文档以了解更多信息:The MongoDB\BSON\Persistable interface
性能
包含约一千个嵌套对象的复杂对象,在廉价笔记本电脑上存储需要 2.5 秒。加载和填充大约需要 1.8 秒。
内部结构
此 ODM 完全依赖于 MongoDB 的 BSON API。您的对象可以是任何您想要的内容:没有注解,没有对构造函数或扩展某些强制具体类的约束。序列化和反序列化是在用 C 编写的驱动程序中完成的,而不是 PHP,这就是为什么它如此快的原因。
测试
此库使用 PHPUnit 进行了全面测试。只需运行
$ vendor/bin/phpunit
DefaultRepositoryTest.php 中可以找到完整功能测试。
迭代器
目前,有一个用于 Iterator 对象的装饰器: ClosureDecorator
。它对于装饰由 MongoDB 存储库(如上所述)创建的游标中的迭代器非常有用。
代码覆盖率
代码覆盖率配置包含在 phpunit.xml
中。只需运行
$ phpdbg -qrr vendor/bin/phpunit
HTML 结果存储在 ./docs/coverage。