Model

A more in-depth look at the MondocAbstractModel, which is the extension source for all top level models in Mondoc.

About the MondocAbstractModel

The MondocAbstractModel class is your ultimate base class for all models in Mondoc. The model represents a MongoDB document, and the class is used to define the structure of that document.

The MondocAbstractModel class extends the MondocAbstractSubModel, which ultimately provides the ability to inflate and deflate models into a suitable format for MongoDB.

Your models can contain almost any type of data, including arrays, objects, and even nest other models.

A MondocAbstractModel also contains the description MondocMongoTypeTrait . The methods listed below also include these type conversion helper methods.

  • getObjectId(): \MongoDB\BSON\ObjectId|null
    Returns the MongoDB ObjectId of the document.
  • hasObjectId(): bool
    Determines if the document has an ObjectId, which ultimately indicates whether the document is new or existing.
    Note:
    Using a preset ObjectId will not make this method return true. The actual ObjectId is only set after the document is saved for the first time, at which point the preset ObjectId is promoted to the ObjectId and the preset is removed from the model.
  • getObjectIdString(): string|null
    Returns the ObjectId as a string. This is useful when you need to pass the ObjectId to another method or class that expects a string.
  • setPresetObjectId(\MongoDB\BSON\ObjectId|null $presetMongoId): static
    Sets a preset ObjectId for the document. This is useful when you want to set the ID of a document before saving it to the database. Any resulting save will call insert, but with the preset ObjectId.
    After insertion, the preset ObjectId is promoted to the ObjectId parameter.
  • save(array $insertOrUpdateOptions = []): bool
    Performs an insert or update operation on the document. The decision of whether to insert or update is based on the presence of an ObjectId, not to be confused with the setPresetObjectId usage.
  • delete(): bool
    Deletes the model from the database.
  • asJsonEncodableArray(array $omitKeys = []): array
    Returns the document as an array that is suitable for JSON encoding. This return is suitable for use in APIs.
    Note:
    This method does not filter out any sensitive data unless you pass the $omitKeys parameter, which is an array of keys to omit from the output.
  • convertDateObject(\MongoDB\BSON\UTCDateTime|\DateTime|null $date, bool $asMongo = false): \MongoDB\BSON\UTCDateTime|\DateTime|null
    Converts a date object to a MongoDB UTCDateTime object or a PHP DateTime object. This is useful when you need to convert a date object to a format that is suitable for MongoDB, or likewise convert a MongoDB date object to a PHP DateTime object.
  • newObjectId(): \MongoDB\BSON\ObjectId
    Generate a new MongoDB ObjectId.
    See also: description Converting types with Mondoc .
  • objectIdToString(\MongoDB\BSON\ObjectId $id): string
    Converts a MongoDB ObjectId to a string.
    See also: description Converting types with Mondoc .
  • toObjectId(\MongoDB\BSON\ObjectId|array|string|null $id): ?\MongoDB\BSON\ObjectId
    Converts a value to a MongoDB ObjectId. This method accepts a wide range of potential types, including an ObjectId, an array, or a string.
    See also: description Converting types with Mondoc .
  • deduplicateArrayOfObjectIds(array $ids): array
    Deduplicates an array of MongoDB ObjectIds.
    See also: description Converting types with Mondoc .
  • arrayToPhp(mixed $item): mixed
    Converts an array to a PHP array. This method is useful when working with MongoDB BSONArray, or BSONDocument objects.
    See also: description Converting types with Mondoc .
  • inc(string $field, int $delta = 1): bool
    Increments a field by a given delta.
  • dec(string $field, int $delta = 1): bool
    Decrements a field by a given delta.
  • isDirtyisDirty(string|null $property): bool
    Determines if the model, or a specific property is dirty. This is used to determine if the model needs to be saved or if there's a specific property which needs to be updated.
  • isDirtyField(string $property): bool
    Determines if a property is dirty. This is used to determine if the property needs to be updated when saving the document.
  • addDirty(string $property): static
    Adds a field to the list of dirty fields. Using it isn't necessary for all fields, as the dirty state is calculated from either it being a new model, or the original BSON document value being different from the current value.
    As of version 6.5.0, Mondoc will no longer requires the use of the addDirty method. Instead, Mondoc now establishes the dirty status by calling isDirty or isDirtyField on the model.
  • getMondocCollectionNameOverride(): ?string
    Optionally override the collection name for the model. This is useful when you need to store the model in a different collection than the default collection name.
    This is an optional method. Default value is as specified in your service.
  • getMondocConnectionIdOverride(): ?string
    Optionally override the connection ID for the model. This is useful when you need to store the model to a different connection than your current connection for the corresponding service
    This is an optional method. Default value is as specified in your service.

Helpful properties include:

  • $mondocNested
    An array of nested model definitions. This is used to define the structure of nested models. This is inherited from the MondocAbstractSubModel class. You can read more about nesting models in description Nested models , but here is a quick example:
    protected Person|null $person = null; // Single Person model
    
    protected array $people = []; // Array of Person models
    
    protected array $mondocNested = [
        'person' => Person::class, // Single nested model
        'people' => Person::class . '[]' // Array of nested models
    ];
  • $mondocFieldAliases
    An array of field aliases to map a remote field to a locally defined property. For example:
    protected array $mondocFieldAliases = [
        'a_db_underscore_key' => 'aLocalCamelCaseKey'
    ];

Below is an example model, as well as the corresponding nested model (underneath), that contains all variable types supported by Mondoc.

Read description Model traits to understand how the included District5\Mondoc\Db\Model\Traits\* alter the behavior of your model.
<?php

namespace MyNamespace;

class AllTypesModel 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\MondocRetentionTrait;
    use \District5\Mondoc\Db\Model\Traits\MondocRevisionNumberTrait;
    use \District5\Mondoc\Db\Model\Traits\MondocVersionedModelTrait;

    protected \MongoDB\BSON\ObjectId|null $anId = null;

    protected string|null $string = null;

    protected int|null $int = null;

    protected mixed $null = null;

    protected float|null $float = null;

    protected bool|null $bool = null;

    protected object|null $object = null;

    protected \DateTime|\MongoDB\BSON\UTCDateTime|null $phpDate = null;

    protected array|null $phpArray = [];

    protected \MyNamespace\SomeSubModel|null $someSub = null;

    protected array $manySubModels = []; // Array of SomeSubModel models

    /**
     * An array holding data on which keys need to be coerced into sub DTOs.
     *
     * @example
     *      [
     *          'property' => '\Full\Class\Name'
     *      ]
     *
     * @var string[]
     */
    protected array $mondocNested = [
        'someSub' => \MyNamespace\SomeSubModel::class,
        'manySubModels' => \MyNamespace\SomeSubModel::class . '[]' // Array of nested models
    ];

    /**
     * An array holding original key to new keys.
     *
     * @example
     *    [
     *        'some_underscore_key' => 'someCamelCaseKey'
     *    ]
     *
     * @var string[]
     */
    protected array $mondocFieldAliases = [
        'a_db_string_key' => 'string'
    ];

    public function setSomeSubModel(\MyNamespace\SomeSubModel $v): void
    {
        $this->someSub = $v;
    }

    public function getSomeSubModel(): \MyNamespace\SomeSubModel|null
    {
        return $this->someSub;
    }

    public function setManySubModels(array $v): void
    {
        $this->manySubModels = $v;
    }

    public function getManySubModels(): array
    {
        return $this->manySubModels; // Array of SomeSubModel models
    }

    public function setAnId(\MongoDB\BSON\ObjectId $v): void
    {
        $this->anId = $v;
    }

    public function getAnId(): \MongoDB\BSON\ObjectId|null
    {
        return $this->anId;
    }

    public function setString(string $v): void
    {
        $this->string = $v;
    }

    public function getString(): string|null
    {
        return $this->string;
    }

    public function setInt(int $v): void
    {
        $this->int = $v;
    }

    public function getInt(): int|null
    {
        return $this->int;
    }

    public function setNull(mixed $v): void
    {
        $this->null = $v;
    }

    public function getNull(): mixed
    {
        return $this->null;
    }

    public function setFloat(float $v): void
    {
        $this->float = $v;
    }

    public function getFloat(): float|null
    {
        return $this->float;
    }

    public function setBool(bool $v): void
    {
        $this->bool = $v;
    }

    public function getBool(): bool|null
    {
        return $this->bool;
    }

    public function setPhpArray(array $v): void
    {
        $this->phpArray = $v;
    }

    public function getPhpArray(): array|null
    {
        return \District5\Mondoc\Helper\MondocTypes::arrayToPhp(
            $this->phpArray
        );
    }

    public function setPhpDate(\DateTime $v): void
    {
        $this->phpDate = $v;
    }

    public function getPhpDate(): \DateTime|null
    {
        return \District5\Mondoc\Helper\MondocTypes::dateToPHPDateTime(
            $this->phpDate
        );
    }

    public function getPhpDateAsMongoDate(): \MongoDB\BSON\UTCDateTime|null
    {
        return \District5\Mondoc\Helper\MondocTypes::phpDateToMongoDateTime(
            $this->phpDate
        );
    }
}
The above example references MondocTypes for some type conversions. You can learn more about this helper by reading the description Converting types with Mondoc page.
<?php
namespace MyNamespace;

class SomeSubModel extends \District5\Mondoc\Db\Model\MondocAbstractSubModel
{
    protected string|null $aField = null;

    public function setAField(string $v): void
    {
        $this->aField = $v;
    }

    public function getAField(): string|null
    {
        return $this->aField;
    }
}
When making edits on a field within a nested model, you can call addDirty('field') on the parent model to ensure the field is updated when saving. This isn't necessary as of version 6.5.0, but still useful if you need to be explicit about the field being dirty and forcing an update.