athenea / mongo-lib
此包的最新版本(7.1.0)没有提供许可信息。
Athenea Solutions 的 MongoDB 工具
7.1.0
2024-07-15 10:13 UTC
Requires
- mongodb/mongodb: ^1.11
- phpdocumentor/reflection-docblock: ^5.3
- symfony/property-access: ^7.0
- symfony/property-info: ^7.0
- symfony/serializer: ^7.0
- symfony/string: ^7.0
Requires (Dev)
- soyuka/stubs-mongodb: ^1.0
README
你好!这个库聚合了多种实用工具,以简化 Athenea Solutions 使用官方 MongoDB 驱动 mongo-php-library。目前包含以下内容:
- 序列化和反序列化工具
- ObjectId 别名
该库目前处于 beta 版本。任何错误报告请发送至 lluc.bove@atheneasolutions.com
安装
composer install {nom a definir}
使用方法
序列化和反序列化
提供了类 Athenea\Mongolib\Model\Base
,它实现了接口 MongoDB\BSON\Serializable
和 MongoDB\BSON\Unserializable
。如果一个类继承自该类,则其实现 Athenea\Mongolib\Attribute\BsonSerialize
属性的字段将自动进行 BSON 的规范化/去规范化。
示例
<?php
use Athenea\MongoLib\Attribute\BsonSerialize;
use Athenea\MongoLib\Model\Base;
use DateTime;
use MongoDB\BSON\ObjectId;
class Persona extends Base {
# Es pot especificar un nom concret amb el camp name
#[BsonSerialize(name: "_id")]
private ObjectId $id;
#[BsonSerialize]
private string $name;
# Els camps amb DateTime es serialitzen a MongoDB/BSON/UTCDateTime i viceversa
#[BsonSerialize]
private DateTime $createdAt;
# Les arrays es serialitzen/deserialitzen recursivament. Cal especificar el tipus de l'array en els comentaris.
#[BsonSerialize]
/**
* @var array<User>
*/
private array $friends;
public function __construct()
{
$this->createdAt = new DateTime();
}
#Cal que els camps tinguin getters i setters o que siguin públic per serialitzar-los
public function getId(): ObjectId
{
return $this->id;
}
public function setId(ObjectId $id): self
{
$this->id = $id;
return $this;
}
public function getCreatedAt(){
return $this->createdAt;
}
public function setCreatedAt(DateTime $createdAt){
$this->createdAt = $createdAt;
}
public function getName(){
return $this->name;
}
public function setName(string $name){
$this->name = $name;
}
public function getFriends(){
return $this->friends;
}
public function setFriends(array $friends){
$this->friends = $friends;
return $this;
}
}
要自动反序列化,需要使用 mongo 库的 typeMap
(typemaps)
$client = new Client("mongodb://");
$db = $client->selectDatabase("bbdd");
$col = $db->selectCollection("persones");
$doc = $col->findOne( [ '_id' => ObjectId("6240de600000000000000000") ], [ 'typeMap' => [ 'root' => Persona::class ] ] );
注意事项
- 所有要序列化/反序列化的字段都必须实现
Athenea\MongoLib\Attribute\BsonSerialize
- 只能序列化/反序列化 mongoDB 的标准元素、基本类型、数组、stdClass 以及实现
MongoDB\BSON\Serializable
或MongoDB\BSON\Unserializable
的类 - 为了正确反序列化,必须设置所有字段的类型,无论是 PHP 还是文档。如果不这样做,将按数据库中的原始格式进行反序列化。
- 可序列化的字段需要实现 getters 和 setters 或是 public
- 类型为
MongoDB/BSON/UTCDateTime
的字段将反序列化为类型MongoDB/BSON/UTCDateTime
,反之亦然 - 反序列化的字段只能有一个类型。如果有多个,则将推断第一个找到的类型。
- 数组和 stdClass 将递归地序列化和反序列化,直到任意深度
ObjectId 别名
use function Athenea\MongoLib\BSON\oid;
$x = $collection->findOne(['_id' => oid("6240de600000000000000000")]);