beecubu/php-foundation-mongodb

PHP Object Foundation Framework Serialization library for MongoDB

Installs: 116

Dependents: 2

Suggesters: 0

Security: 0

pkg:composer/beecubu/php-foundation-mongodb

v1.6.2 2025-04-22 23:26 UTC

This package is auto-updated.

Last update: 2026-02-04 12:35:29 UTC


README

MongoDB integration for PHP Object Foundation. It provides:

  • Serializable Entity classes with MongoDB-compatible IDs and types.
  • A lightweight MongoDB driver wrapper (MongoClient, MongoDB, MongoCollection).
  • Base DB connection helper (DBConnection).

Requirements

  • PHP 7.1+
  • ext-mongodb >= 1.4.0
  • beecubu/php-foundation-core
  • beecubu/php-foundation-helpers

Installation

composer require beecubu/php-foundation-mongodb

Entity Types

  • Entity: Uses MongoDB _id (ObjectId) and converts DateTime to UTCDateTime.
  • PlainEntity: Same as Entity but does not convert ids to MongoDB ObjectId.
  • ExplicitEntity: Same as Entity but always serializes _class.
  • PlainExplicitEntity: Same as PlainEntity but always serializes _class.

Basic Entity Example

<?php

use Beecubu\Foundation\MongoDB\Entity;
use Beecubu\Foundation\Core\Property;

class User extends Entity
{
    protected function properties(): void
    {
        parent::properties();
        $this->properties += [
            'name'  => [Property::READ_WRITE, Property::IS_STRING],
            'email' => [Property::READ_WRITE, Property::IS_STRING],
        ];
    }
}

DB Connection

Define MongoDB constants:

define('MONGO_SERVER', 'localhost:27017');
define('MONGO_DATABASE', 'my_app');

Then extend DBConnection to access collections:

<?php

use Beecubu\Foundation\MongoDB\DBConnection\DBConnection;

class UsersDB extends DBConnection
{
    public function users()
    {
        return $this->db->users;
    }
}

Driver Usage

use Beecubu\Foundation\MongoDB\Driver\MongoClient;

$client = new MongoClient('mongodb://localhost:27017');
$db = $client->my_app;
$users = $db->users;

$users->insert(['name' => 'Ada']);
$doc = $users->findOne(['name' => 'Ada']);
$users->update(['_id' => $doc->_id], ['$set' => ['name' => 'Ada Lovelace']]);
$users->remove(['_id' => $doc->_id]);

Notes

  • Collections are accessed as properties: $db->users.
  • MongoCollection supports find, findOne, findAndModify, insert, update, save, remove, aggregate, distinct, count, exists, and drop.