PHP code example of district5 / mondoc

1. Go to this page and download the library: Download district5/mondoc library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

district5 / mondoc example snippets



use District5\Mondoc\MondocConfig;
use MongoDB\Client;

$connection = new Client('< mongo connection string >');
$database = $connection->selectDatabase('< database name >');

$config = MondocConfig::getInstance();
$config->addDatabase(
    $database,
    'default' // a connection identifier ('default' is the default value).
);
// Add another one for something else...
// $config->addDatabase(
//     $database,
//     'authentication'
// );


$config->addServiceMapping(
    MyModel::class, // You can also just use a string like '\MyNamespace\Model\MyModel'
    MyService::class // You can also just use a string like '\MyNamespace\Service\MyService'
);
// Or you can use...
// $config->setServiceMap(
//     [
//         MyModel::class => MyService::class, // Also replaceable by strings
//         AnotherModel::class => AnotherService::class,
//     ]
// );



namespace MyNs\Model;

use District5\Mondoc\Db\Model\MondocAbstractModel;

/**
 * Class MyModel
 * @package MyNs\Model
 */
class MyModel extends MondocAbstractModel
{
    /**
     * @var string
     */
    protected $name = null;
    
    // This is optional, but can be used to map fields from the database to the model to keep keys short in storage.
    protected array $mondocFieldAliases = [
        'n' => 'name', // the `name` value would be stored in the database as the key `n`
    ];

    /**
     * @return string
     */
    public function getName(): ?string
    {
        return $this->name;
    }

    /**
     * @param string $val
     * @return $this
     */
    public function setName(string $val)
    {
        $this->name = trim($val);
        $this->addDirty('name');
        return $this;
    }
}

namespace MyNs\Model;

use District5\Mondoc\Db\Model\MondocAbstractModel;

class MyModel extends MondocAbstractModel
{
    protected string $name = null;
    
    protected array $mondocFieldAliases = [
        'n' => 'name',
    ];

    // Rest of your model code...
}


class MyModel extends \District5\Mondoc\Db\Model\MondocAbstractModel
{
    use \District5\Mondoc\Db\Model\Traits\MondocCreatedDateTrait;
    use \District5\Mondoc\Db\Model\Traits\MondocModifiedDateTrait;
    use \District5\Mondoc\Db\Model\Traits\MondocCloneableTrait;
    use \District5\Mondoc\Db\Model\Traits\MondocRevisionNumberTrait;
    use \District5\Mondoc\Db\Model\Traits\MondocVersionedModelTrait;
    use \District5\Mondoc\Db\Model\Traits\MondocRetentionTrait;
    
    // Rest of your model code...
}


namespace Myns\Service;

use MyNs\Model\MyModel;
use District5\Mondoc\Db\Service\MondocAbstractService

/**
 * Class MyService
 * @package MyNs\Service
 */
class MyService extends MondocAbstractService
{
    /**
     * Get the collection name.
     *
     * @return string
     */
    protected static function getCollectionName(): string
    {
        return 'users';
    }
    
    /**
     * Get the connection ID to use from the MondocConfig manager. Defaults to 'default'.
     * This method isn't 

protected Food $favouriteFood;
protected array $allFoods; // Array of 'Food' objects

protected array $mondocNested = [
    'favouriteFood' => Food::class, // Single nested model
    'allFoods' => Food::class . '[]' // Array of nested models
];

protected Food $favouriteFood;
protected array $allFoods; // Array of 'Food' objects

protected array $mondocFieldAliases = [
    'ff' => 'favouriteFood',
    'af' => 'allFoods'
];

use District5\Mondoc\Db\Model\MondocAbstractModel;
use District5\Mondoc\Db\Model\MondocAbstractSubModel;

class FavouriteFood extends MondocAbstractSubModel
{
    protected string $foodName;

    protected string $foodDescription;

    // This is optional, but can be used to map fields from the database to the model to keep keys short in storage
    protected array $mondocFieldAliases = [
        'fd' => 'foodDescription',
    ];

    public function getFoodName()
    {
        return $this->foodName;
    }

    public function getFoodDescription()
    {
        return $this->foodDescription;
    }
}

class Car extends MondocAbstractSubModel
{
    protected string|null $brand = null;
    protected string|null $colour = null;
    
    public function getBrand(): ?string
    {
        return $this->brand;
    }
    
    public function getColour(): ?string
    {
        return $this->colour;
    }
}

class Person extends MondocAbstractModel
{
    /**
     * @var string|null
     */
    protected string|null $name = null;
    
    /**
     * @var FavouriteFood 
     */
    protected FavouriteFood|null $favouriteFood = null; // Having BSONDocument here is important as inflation will use the property
    
    /**
     * @var FavouriteFood[]
     */
    protected array $allFoods = []; // Having BSONArray here is important as inflation will use the property
    
    /**
     * @var Car 
     */
    protected Car|null $car = null; // Having BSONDocument here is important as inflation will use the property
    
    /**
     * @var string[] 
     */
    protected array $mondocNested = [
        'allFoods' => FavouriteFood::class . '[]', // Indicates an array of FavouriteFood objects
        'favouriteFood' => FavouriteFood::class,
        'car' => Car::class
    ];

    public function getAllFoods(): array
    {
        return $this->allFoods;
    }

    public function getFavouriteFoodName(): ?string
    {
        return $this->favouriteFood->getFoodName();
    }

    public function getCarBrand(): ?string
    {
        return $this->car->getBrand();
    }

    public function getCarColour(): ?string
    {
        return $this->car->getColour();
    }
}



// count documents matching a filter
\District5Tests\MondocTests\TestObjects\MyService::countAll([], []);
// count documents using a query builder
$builder = \District5Tests\MondocTests\TestObjects\MyService::getQueryBuilder();
\District5Tests\MondocTests\TestObjects\MyService::countAllByQueryBuilder($builder);

// get single model by id, accepts a string or ObjectId
\District5Tests\MondocTests\TestObjects\MyService::getById('the-mongo-id');

// get multiple models by ids. accepts string or ObjectIds
\District5Tests\MondocTests\TestObjects\MyService::getByIds(['an-id', 'another-id']);

// get single model with options
\District5Tests\MondocTests\TestObjects\MyService::getOneByCriteria(['foo' => 'bar'], ['sort' => ['foo' => -1]]);

// get multiple models with options
\District5Tests\MondocTests\TestObjects\MyService::getMultiByCriteria(['foo' => 'bar'], ['sort' => ['foo' => -1]]);

// working with dates, both of these queries are the same
$phpDate = new \DateTime();
\District5Tests\MondocTests\TestObjects\MyService::getMultiByCriteria(['dateField' => ['$lte' => $phpDate]]);
$mongoDate = \District5\Mondoc\Helper\MondocTypes::phpDateToMongoDateTime($phpDate);
\District5Tests\MondocTests\TestObjects\MyService::getMultiByCriteria(['dateField' => ['$lte' => $mongoDate]]);

// paginating results by page number
$currentPage = 1;
$perPage = 10;
$sortByField = 'foo';
$sortDirection = -1;
$pagination = \District5Tests\MondocTests\TestObjects\MyService::getPaginationHelper($currentPage, $perPage, ['foo' => 'bar'])
$results = \District5Tests\MondocTests\TestObjects\MyService::getPage($pagination, $sortByField, $sortDirection); // Since 6.3.0 the filter is carried through by the pagination helper

// paginating results by ID number descending (first page)
$currentId = null;
$perPage = 10;
$sortDirection = -1;
$pagination = \District5Tests\MondocTests\TestObjects\MyService::getPaginationHelperForObjectIdPagination($perPage, ['foo' => 'bar'])
$results = \District5Tests\MondocTests\TestObjects\MyService::getPageByByObjectIdPagination($pagination, $currentId, $perPage, $sortDirection); // Since 6.3.0 the filter is carried through by the pagination helper

// paginating results by ID number descending
$currentId = '5f7deca120c41f29827c0c60'; // or new ObjectId('5f7deca120c41f29827c0c60');
$perPage = 10;
$sortDirection = -1;
$pagination = \District5Tests\MondocTests\TestObjects\MyService::getPaginationHelperForObjectIdPagination($perPage, ['foo' => 'bar'])
$results = \District5Tests\MondocTests\TestObjects\MyService::getPageByByObjectIdPagination($pagination, $currentId, $perPage, $sortDirection); // Since 6.3.0 the filter is carried through by the pagination helper

// paginating results by ID number ascending
$currentId = '5f7deca120c41f29827c0c60'; // or new ObjectId('5f7deca120c41f29827c0c60');
$perPage = 10;
$sortDirection = 1;
$pagination = \District5Tests\MondocTests\TestObjects\MyService::getPaginationHelperForObjectIdPagination($perPage, ['foo' => 'bar'])
$results = \District5Tests\MondocTests\TestObjects\MyService::getPageByByObjectIdPagination($pagination, $currentId, $perPage, $sortDirection); // Since 6.3.0 the filter is carried through by the pagination helper

// get the distinct values for 'age' with a filter and options
\District5Tests\MondocTests\TestObjects\MyService::getDistinctValuesForKey('age', ['foo' => 'bar'], ['sort' => ['age' => 1]]);

// average age with filter
\District5Tests\MondocTests\TestObjects\MyService::aggregate()->getAverage('age', ['foo' => 'bar']);

// 10% percentile, sorted asc with filter
\District5Tests\MondocTests\TestObjects\MyService::aggregate()->getPercentile('age', 0.1, 1, ['foo' => 'bar']);

// get sum of a field with a given filter
\District5Tests\MondocTests\TestObjects\MyService::aggregate()->getSum('age', ['foo' => 'bar']);

// get the min value of a field with a given filter
\District5Tests\MondocTests\TestObjects\MyService::aggregate()->getMin('age', ['foo' => 'bar']);
// ...or with a string...
// \District5Tests\MondocTests\TestObjects\MyService::aggregate()->getMin('name', ['foo' => 'bar']);

// get the max value of a field with a given filter
\District5Tests\MondocTests\TestObjects\MyService::aggregate()->getMax('age', ['foo' => 'bar']);
// ...or with a string...
// \District5Tests\MondocTests\TestObjects\MyService::aggregate()->getMax('name', ['foo' => 'bar']);

/* @var $model \District5\Mondoc\Db\Model\MondocAbstractModel */

$mongoInsertionDocument = $model->asArray(); // Not encodable to JSON
$jsonEncodable = $model->asJsonEncodableArray(); // Encodable to JSON
$jsonEncodable = $model->asJsonEncodableArray(['password', 'secret']); // Encodable to JSON omitting the 'password' and 'secret' properties

$encodedJson = json_encode($jsonEncodable, JSON_THROW_ON_ERROR);
echo $encodedJson;


/** @noinspection SpellCheckingInspection */
$theId = new \MongoDB\BSON\ObjectId('61dfee5591efcf44e023d692');

$person = new Person();
$person->setPresetObjectId(new ObjectId());
$insertOrUpdateOptions = [];
$person->save($insertOrUpdateOptions); // optional

echo $person->getObjectIdString(); // 61dfee5591efcf44e023d692


use District5\Mondoc\Db\Model\MondocAbstractModel;

class MyModel extends MondocAbstractModel
{
    protected string $name = null;
    protected int $version = 0;

    protected function assignDefaultVars()
    {
        if ($this->version < 1) {
            $this->version = 1;
        }
    }
}


use \District5\Mondoc\Helper\MondocTypes;

// Dates
$mongoDateTime = MondocTypes::phpDateToMongoDateTime(new \DateTime());
$phpDateTime = MondocTypes::dateToPHPDateTime($mongoDateTime);

// BSON documents
$bsonDocument = new \MongoDB\Model\BSONDocument(['foo' => 'bar']);
$phpArrayFromDoc = MondocTypes::arrayToPhp($bsonDocument);

// BSON arrays
$bsonArray = new \MongoDB\Model\BSONArray(['foo', 'bar']);
$phpArrayFromArray = MondocTypes::arrayToPhp($bsonArray);

// ObjectIds
/** @noinspection SpellCheckingInspection */
$anId = '61dfee5591efcf44e023d692';
$objectId = MondocTypes::toObjectId($anId);
// You can also pass existing ObjectId's into the conversion and nothing happens.
// MondocTypes::toObjectId(new \MongoDB\BSON\ObjectId());
// MondocTypes::toObjectId($objectId);

$string = MondocTypes::objectIdToString($objectId);

// less used, but still handled...
$objectId = MondocTypes::toObjectId([
    '$oid' => '61dfee5591efcf44e023d692'
]);
$objectId = MondocTypes::toObjectId([
    'oid' => '61dfee5591efcf44e023d692'
]);



use District5\Date\Date;
use District5\Mondoc\Db\Model\MondocAbstractModel;
use District5\Mondoc\Db\Model\Traits\MondocRetentionTrait;
use District5\Mondoc\Helper\MondocTypes;
use District5\Mondoc\Extensions\Retention\MondocRetentionService;

class MyService extends MondocAbstractService
{
    protected static function getCollectionName(): string
    {
        return 'data';
    }
}

class MyModel extends MondocAbstractModel
{
    use MondocRetentionTrait;

    protected string $name = null;

    public function setName(string $name): self
    {
        $this->name = $name;
        $this->addDirty('name');
        return $this;
    }
}

$model = new MyModel();
$model->setName('John Doe');
$model->setMondocRetentionData([
    'user' => 'joe.bloggs',
]);
$model->setMondocRetentionExpiry(
    Date::modify(
        Date::nowUtc()
    )->plus()->days(30)
);
$model->save();

// There is now both a `MyModel` saved, and a `MondocRetentionModel` saved with the retention data.
$retrieved = MyService::getById($model->getObjectIdString());
$retrieved->setMondocRetentionData([
    'user' => 'jane.bloggs',
]);
$retrieved->setMondocRetentionExpiry(
    null // this data will never expire
);
$retrieved->save();

// A new `MondocRetentionModel` is saved with the updated retention data. There are now two `MondocRetentionModel`'s

$paginator = MondocRetentionService::getRetentionHistoryPaginationHelperForClassName(
    MyModel::class,
    1,
    10,
    ['user' => 'joe.bloggs']
);
$results = MondocRetentionService::getPage(
    $paginator // The filter is carried through by the pagination helper
);
// This will return the `MongoRetentionModel` for the `MyModel` with the user `joe.bloggs`
$firstResultInflated = $results[0]->toOriginalModel();
echo $firstResultInflated->getName(); // John Doe


use District5\Mondoc\Db\Model\MondocAbstractSubModel;

class MyModel extends MondocAbstractSubModel
{
    protected array $mondocFieldAliases = [
        'n' => 'name',
    ];
    
    // Rest of your model code...
}

$wontWork = new \District5\Mondoc\Db\Builder\MondocBuilder\MondocBuilder();
$wontWork->addFilter('name', 'John'); // This WILL NOT WORK with the field mapping

$willWork = new \District5\Mondoc\Db\Builder\MondocBuilder\MondocBuilder();
$willWork->addFilter('n', 'John'); // This will work with the field mapping