beecubu / php-foundation-mongodb
PHP Object Foundation Framework Serialization library for MongoDB
v1.6.2
2025-04-22 23:26 UTC
Requires
- php: >=7.1.0
- ext-mongodb: >=1.4.0
- beecubu/php-foundation-core: ^3.1
- beecubu/php-foundation-helpers: ^1.8
README
MongoDB integration for PHP Object Foundation. It provides:
- Serializable
Entityclasses 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.0beecubu/php-foundation-corebeecubu/php-foundation-helpers
Installation
composer require beecubu/php-foundation-mongodb
Entity Types
Entity: Uses MongoDB_id(ObjectId) and convertsDateTimetoUTCDateTime.PlainEntity: Same asEntitybut does not convert ids to MongoDBObjectId.ExplicitEntity: Same asEntitybut always serializes_class.PlainExplicitEntity: Same asPlainEntitybut 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. MongoCollectionsupportsfind,findOne,findAndModify,insert,update,save,remove,aggregate,distinct,count,exists, anddrop.