PHPackages                             athenea/mongo-lib - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. athenea/mongo-lib

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

athenea/mongo-lib
=================

Mongo utilities for Athenea Solutions

8.1.2(1mo ago)05.9k↓59.1%PHPCI failing

Since Mar 30Pushed 1mo agoCompare

[ Source](https://github.com/atheneasolutions/php-mongo-lib)[ Packagist](https://packagist.org/packages/athenea/mongo-lib)[ RSS](/packages/athenea-mongo-lib/feed)WikiDiscussions main Synced 2d ago

READMEChangelog (10)Dependencies (33)Versions (42)Used By (0)

Athenea MongoLib
================

[](#athenea-mongolib)

PHP library for BSON serialization/deserialization with MongoDB. Provides a `Base` model class that implements `MongoDB\BSON\Serializable` and `MongoDB\BSON\Unserializable`, automatically converting typed PHP objects to and from BSON documents.

Installation
------------

[](#installation)

```
composer require athenea/mongo-lib
```

### Requirements

[](#requirements)

DependencyVersionPurposePHP≥ 8.1Runtime`mongodb/mongodb`^1.0 || ^2.0MongoDB driver`phpdocumentor/reflection-docblock`^5.3`@var` docblock parsing for collection types`symfony/property-info`^5.0 || ^6.0 || ^7.0 || ^8.0Property type introspection`symfony/property-access`^5.0 || ^6.0 || ^7.0 || ^8.0Private property read/write> **Note:** `symfony/serializer` is **not** a direct dependency. Discriminator maps use our own `#[BsonDiscriminator]` attribute (Symfony's `#[DiscriminatorMap]` is also supported as a fallback).

Quick Start
-----------

[](#quick-start)

### Define a model

[](#define-a-model)

```
use Athenea\MongoLib\Attribute\BsonSerialize;
use Athenea\MongoLib\Model\Base;
use MongoDB\BSON\ObjectId;
use DateTime;

class Person extends Base
{
    #[BsonSerialize(name: '_id')]
    private ?ObjectId $id = null;

    #[BsonSerialize]
    private ?string $name = null;

    #[BsonSerialize]
    private ?DateTime $createdAt = null;

    // Getters and setters required for private properties
    public function getName(): ?string { return $this->name; }
    public function setName(?string $name): void { $this->name = $name; }
    public function getCreatedAt(): ?DateTime { return $this->createdAt; }
    public function setCreatedAt(?DateTime $createdAt): void { $this->createdAt = $createdAt; }
    public function getId(): ?ObjectId { return $this->id; }
    public function setId(?ObjectId $id): void { $this->id = $id; }
}
```

### Serialize to BSON

[](#serialize-to-bson)

```
$person = new Person();
$person->setName('Alice');
$person->setCreatedAt(new DateTime());

$bson = $person->bsonSerialize();
// { "_id": null, "name": "Alice", "created_at": UTCDateTime(...) }
```

### Deserialize from BSON

[](#deserialize-from-bson)

```
$person = new Person();
$person->bsonUnserialize([
    '_id' => new ObjectId(),
    'name' => 'Bob',
    'created_at' => new UTCDateTime(),
]);
```

### Compute diffs for partial updates

[](#compute-diffs-for-partial-updates)

```
$changes = $oldPerson->bsonChanges($newPerson);
// ['$set' => ['name' => 'Bob'], '$unset' => ['deleted_at' => '']]
```

### Use with MongoDB collection

[](#use-with-mongodb-collection)

```
$doc = $collection->findOne(
    ['_id' => new ObjectId('6240de600000000000000000')],
    ['typeMap' => ['root' => Person::class]]
);
// $doc is a hydrated Person instance
```

---

Architecture
------------

[](#architecture)

```
src/
├── Attribute/
│   ├── BsonSerialize.php           # Marks properties for BSON serialization
│   └── BsonDiscriminator.php       # Polymorphic discriminator (replaces Symfony's)
├── Metadata/
│   ├── BsonMetadata.php            # Value object: serializable + deserializable props
│   ├── BsonSerializableProperty.php
│   ├── BsonDeserializableProperty.php
│   ├── BsonPropertyType.php       # Value object: className, isCollection, isNullable
│   ├── BsonDiscriminatorMap.php    # Value object: typeProperty + mapping
│   ├── BsonMetadataResolverInterface.php
│   ├── AbstractBsonMetadataResolver.php  # Base resolver (uses PropertyInfoExtractor)
│   └── Symfony/
│       ├── Symfony62MetadataResolver.php  # SF 5.x / 6.x type resolution
│       └── Symfony7MetadataResolver.php   # SF 7.x / 8.x type resolution
├── PropertyAccess/
│   ├── BsonPropertyAccessorInterface.php
│   └── SymfonyPropertyAccessor.php        # Delegates to Symfony PropertyAccess
├── Serializer/
│   ├── BsonSerializer.php          # Core serializer (zero Symfony imports)
│   └── BsonSerializerInterface.php # Public contract
├── Model/
│   └── Base.php                    # Abstract base class
├── Aggregation/
│   ├── AbstractAggregation.php
│   └── MongoAggregation.php
├── Utils.php
└── bson.php                        # oid() helper function

```

### Framework-agnostic core

[](#framework-agnostic-core)

The **`Serializer/BsonSerializer.php`** has **zero Symfony imports**. All framework coupling is isolated in adapter files:

ConcernInterfaceSymfony AdapterProperty access`BsonPropertyAccessorInterface``SymfonyPropertyAccessor`Metadata resolution`BsonMetadataResolverInterface``Symfony62MetadataResolver` / `Symfony7MetadataResolver`Type introspection—`AbstractBsonMetadataResolver` (uses `PropertyInfoExtractor`)The serializer auto-detects the Symfony version at runtime and instantiates the correct resolver.

---

Reference
---------

[](#reference)

### `#[BsonSerialize]` attribute

[](#bsonserialize-attribute)

Marks a property for BSON serialization/deserialization.

```
#[BsonSerialize]                    // uses snake_case of property name as BSON field
#[BsonSerialize(name: '_id')]      // explicit BSON field name
```

**Rules:**

- Private/protected properties require a getter (for serialization) and a setter (for deserialization), or be public.
- The `name` parameter is the BSON field name. If omitted, the property name is converted to `snake_case`.
- `DateTime` properties are automatically converted to/from `UTCDateTime`.
- `BackedEnum` properties are automatically converted to/from their scalar value.

### `#[BsonDiscriminator]` attribute

[](#bsondiscriminator-attribute)

Declares a discriminator map on an abstract class for polymorphic deserialization.

```
use Athenea\MongoLib\Attribute\BsonDiscriminator;

#[BsonDiscriminator('type', [
    'cat' => CatModel::class,
    'dog' => DogModel::class,
])]
abstract class AbstractAnimal extends Base
{
    #[BsonSerialize]
    private ?string $type = null;
}

class CatModel extends AbstractAnimal
{
    #[BsonSerialize]
    private ?int $lives = null;
}
```

When deserializing, the serializer reads `$data['type']` and instantiates the matching concrete class.

**Symfony `#[DiscriminatorMap]` fallback:** If your project already uses Symfony's serializer with `#[DiscriminatorMap]`, it works too — no changes needed.

### Supported types

[](#supported-types)

PHP typeBSON representationExample`string`, `int`, `float`, `bool`Direct`name: 'Alice'``?string` (nullable)Direct or skip`name: null` → property skipped`DateTime`, `DateTimeInterface``UTCDateTime`Automatic conversion`ObjectId``ObjectId`Preserved as-is`BackedEnum`scalar value`Status::Active` → `1``array`, `stdClass`RecursiveNested serialization`Base` subclassRecursive `bsonSerialize()`Nested models`array`Recursive with `@var`See collection types below### Collection types with `@var`

[](#collection-types-with-var)

PHP type hints don't express generic arrays (`array`). Use `@var` docblocks:

```
#[BsonSerialize]
/** @var SimpleModel[] */
private array $items = [];
```

The metadata resolver reads `@var` annotations via `phpdocumentor/reflection-docblock` (through `symfony/property-info`) and deserializes each element as `SimpleModel`.

### ObjectId helper

[](#objectid-helper)

```
use function Athenea\MongoLib\BSON\oid;

$document = $collection->findOne(['_id' => oid('6240de600000000000000000')]);
```

---

Testing
-------

[](#testing)

```
# Run tests (requires Symfony 8.0 by default)
vendor/bin/phpunit

# Test across all supported Symfony versions
php bin/test-all-symfony-versions.php
```

The cross-version script temporarily installs each Symfony version, runs the test suite, and restores the original `composer.json`.

---

License
-------

[](#license)

MIT License. See [LICENSE](./LICENSE) for details.

###  Health Score

50

—

FairBetter than 95% of packages

Maintenance94

Actively maintained with recent releases

Popularity22

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 95.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~41 days

Recently: every ~3 days

Total

38

Last Release

32d ago

Major Versions

1.1.16 → 7.0.02024-02-12

1.2.0 → 7.1.02024-07-15

7.2.2 → 8.0.02026-01-28

7.0.x-dev → 8.0.12026-01-29

7.3.0 → 8.0.22026-05-20

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/203246?v=4)[athenea](/maintainers/athenea)[@athenea](https://github.com/athenea)

---

Top Contributors

[![lluc-athenea](https://avatars.githubusercontent.com/u/56869917?v=4)](https://github.com/lluc-athenea "lluc-athenea (45 commits)")[![marmelichathenea](https://avatars.githubusercontent.com/u/253458994?v=4)](https://github.com/marmelichathenea "marmelichathenea (2 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/athenea-mongo-lib/health.svg)

```
[![Health](https://phpackages.com/badges/athenea-mongo-lib/health.svg)](https://phpackages.com/packages/athenea-mongo-lib)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[pimcore/pimcore

Content &amp; Product Management Framework (CMS/PIM/E-Commerce)

3.8k3.8M507](/packages/pimcore-pimcore)[2lenet/crudit-bundle

The easy like Crud'it Bundle.

1616.4k14](/packages/2lenet-crudit-bundle)[api-platform/core

Build a fully-featured hypermedia or GraphQL API in minutes!

2.6k51.2M339](/packages/api-platform-core)[web-auth/webauthn-lib

FIDO2/Webauthn Support For PHP

12310.5M135](/packages/web-auth-webauthn-lib)[oro/platform

Business Application Platform (BAP)

645143.5k115](/packages/oro-platform)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
