composer install fatcode/storage
<?php
use FatCode\Storage\Driver\MongoDb\MongoConnection;
use FatCode\Storage\Driver\MongoDb\MongoConnectionOptions;
$connection = new MongoConnection('localhost', new MongoConnectionOptions('dbName'));<?php
use FatCode\Storage\Driver\MongoDb\MongoConnectionOptions;
$options = new MongoConnectionOptions('dbName', 'username', 'secret');<?php
use FatCode\Storage\Driver\MongoDb\MongoConnection;
use FatCode\Storage\Driver\MongoDb\MongoConnectionOptions;
$options = new MongoConnectionOptions('dbName', 'username', 'secret');
$options->setReplicaSet('replicaSetName');
$connection = new MongoConnection(['localhost:27017', 'localhost:27018'], $options);Storage recommends using
MongoDB\BSON\ObjectIdas id for all of your documents, but it is not enforced, so any value can be passed to methods that accepts$idproperty. It is also recommended to implement__toStringinterface if you are planning passing any objects as an id.
<?php
use FatCode\Storage\Driver\MongoDb\MongoConnection;
/** @var MongoConnection $connection */
$connection->createCollection('myCollection');
// or simply access the collection and it will be created on runtime
$connection->myCollection;Collection can be created in two ways:
- Executing
CreateCollectioncommand which accepts collection name as first argument and collocation as second one - Directly accessing the collection and inserting new document
<?php
use FatCode\Storage\Driver\MongoDb\MongoConnection;
/** @var MongoConnection $connection */
$connection->dropCollection('myCollection');The following code will return array of collection names.
<?php
use FatCode\Storage\Driver\MongoDb\MongoConnection;
/** @var MongoConnection $connection */
$connection->listCollections();Following example creates new document containing names field. Once operation is executed boolean flag is returned
to indicate either success (true) of failure (false)
<?php
use MongoDB\BSON\ObjectId;
use FatCode\Storage\Driver\MongoDb\MongoConnection;
$myFavouritesColors = [
'_id' => new ObjectId(),// its always recommended to generate id manually,
// so the state is final before document is persisted
'names' => ['black', 'black', 'black']
];
/** @var MongoConnection $connection */
$success = $connection->myCollection->insert($myFavouritesColors);Document can only be updated if it contains _id field, please check the following example:
<?php
use MongoDB\BSON\ObjectId;
use FatCode\Storage\Driver\MongoDb\MongoConnection;
$myFavouritesColors = [
'_id' => new ObjectId('5c929b31cb406a2cd4106bb2'),
'names' => ['black', 'black', 'black', 'white']
];
/** @var MongoConnection $connection */
$connection->myCollection->update($myFavouritesColors);Once document is updated the boolean flag is returned indicating whether operation was successful.
Document can be removed, by simply passing its id to $collection->delete:
<?php
use MongoDB\BSON\ObjectId;
use FatCode\Storage\Driver\MongoDb\MongoConnection;
/** @var MongoConnection $connection */
$connection->myCollection->delete(new ObjectId('5c929b31cb406a2cd4106bb2'));<?php
use FatCode\Storage\Driver\MongoDb\MongoConnection;
/** @var MongoConnection $connection */
$connection->myCollecion->findAndDelete(['name' => 'Bob']);Above example deletes all documents that contains property name with assigned string value Bob.
Upsert should be used in case when document presence in collection is unknown (we dont know if document exists in database already or not).
Upsert either creates document if it does not exists in collection or updates existing one, like in update operation _id
field must be defined during upsert operation.
<?php
use MongoDB\BSON\ObjectId;
use FatCode\Storage\Driver\MongoDb\MongoConnection;
$myFavouritesColors = [
'_id' => new ObjectId('5c929b31cb406a2cd4106bb2'),
'names' => ['black', 'black', 'black', 'white']
];
/** @var MongoConnection $connection */
$connection->myCollection->upsert($myFavouritesColors);All above examples are just sugar syntax to simplify daily tasks, when you deal with complex queries is always better
to use mongo commands (commands live in FatCode\Storage\Driver\MongoDb\Command namespace).
The following list contains all built-in supported commands:
FatCode\Storage\Driver\MongoDb\Command\AggregateFatCode\Storage\Driver\MongoDb\Command\CreateCollectionFatCode\Storage\Driver\MongoDb\Command\DropCollectionFatCode\Storage\Driver\MongoDb\Command\ListCollectionsFatCode\Storage\Driver\MongoDb\Command\FindFatCode\Storage\Driver\MongoDb\Command\InsertFatCode\Storage\Driver\MongoDb\Command\RemoveFatCode\Storage\Driver\MongoDb\Command\RemoveByIdFatCode\Storage\Driver\MongoDb\Command\Update
List will grow with time, but there is no limitation if comes to using user defined commands.
Each command can be executed simply by passing its instance to execute method. The method always returns a cursor.
<?php
use MongoDB\BSON\ObjectId;
use FatCode\Storage\Driver\MongoDb\MongoConnection;
use FatCode\Storage\Driver\MongoDb\Command\Find;
/** @var MongoConnection $connection */
$cursor = $connection->execute(new Find('myCollection', ['_id' => new ObjectId('5c929b31cb406a2cd4106bb2')]));
var_dump($cursor->current()); // Will dump document retrieved by its id\FatCode\Storage\Driver\MongoDb\MongoCursor is returned by execute method each time it performs successful command execution.
The cursor fetches results from the handle, and can be iterated through like any iterable object. Cursor does not
caches the results so current's iteration result lives till next iteration, to prevent this scenario you can
for example assign each iteration result in an array like in the following example:
<?php
use FatCode\Storage\Driver\MongoDb\MongoConnection;
use FatCode\Storage\Driver\MongoDb\Command\Find;
/** @var MongoConnection $connection */
$cursor = $connection->execute(new Find('users', ['name' => 'Tom']));
$myUserList = [];
/** @var array $user */
foreach ($cursor as $user) {
$myUserList[] = $user;
}Hydration is a process of populating object from a set of data. Storage library provides mechanisms and interfaces for both hydrating and extracting data sets.
Before hydration can take place a schema object has to be defined.
Schema is an object describing how dataset should be hydrated or extracted and its used by \FatCode\Storage\Hydration\ObjectHydrator.
The following code defines example user class and its schema:
<?php
use FatCode\Storage\Hydration\Schema;
use FatCode\Storage\Hydration\Type;
class MyUser
{
private $id;
private $name;
private $age;
private $interests = [];
}
class MyUserSchema extends Schema
{
protected $id;
protected $name;
protected $age;
protected $interests;
public function __construct()
{
$this->id = Type::id();
$this->name = Type::string();
$this->age = Type::integer();
$this->interests = Type::array();
}
public function getTargetClass() : string
{
return MyUser::class;
}
}\FatCode\Storage\Hydration\ObjectHydrator implements generic functionality for \FatCode\Storage\Hydration\Hydrator
and \FatCode\Storage\Hydration\Extractor to allow simple hydration/extraction of datasets.
In order to hydrate or extract object, a schema must be recognized by ObjectHydrator, it can be achieved both ways:
- by passing schema to
\FatCode\Storage\Hydration\ObjectHydrator::addSchema - registering instance of
\FatCode\Storage\Hydration\SchemaLoaderin\FatCode\Storage\Hydration\ObjectHydrator::addSchemaLoader
For now we will focus on the first one.
<?php
use FatCode\Storage\Hydration\ObjectHydrator;
$objectHydrator = new ObjectHydrator();
$objectHydrator->addSchema(new MyUserSchema());The above code registers schema presented in the previous chapter. From this point on any instance of MyUser class can
be hydrated or extracted.
<?php
use FatCode\Storage\Hydration\ObjectHydrator;
use FatCode\Storage\Hydration\Instantiator;
use MongoDB\BSON\ObjectId;
$objectHydrator = new ObjectHydrator();
$objectHydrator->addSchema(new MyUserSchema());
// Hydration
$bob = $objectHydrator->hydrate(
[
'id' => new ObjectId(),
'name' => 'Bob',
'age' => 30,
'interests' => ['Flowers', 'Judo', 'Milf$']
],
Instantiator::instantiate(MyUser::class)
);Because hydrate method requires instance of recognized class to be passed we used here Instantiator::instatiate,
which is convenient utility tool used to create empty instances of the passed class.
<?php
use FatCode\Storage\Hydration\ObjectHydrator;
$objectHydrator = new ObjectHydrator();
$objectHydrator->addSchema(new MyUserSchema());
// ...
// lets reuse instance created in previous example
$dataset = $objectHydrator->extract($bob);