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 include the most commonly used of these type conversion helpers. The
full set (including newObjectIdFromDateObject, arrayOfObjectIdsToObjectIds,
dateToPHPDateTime and phpDateToMongoDateTime) is also available statically on
MondocTypes.
-
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 presetObjectIdwill not make this method returntrue. The actualObjectIdis 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
setPresetObjectIdusage. -
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$omitKeysparameter, 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 protected
Protected: only callable from inside your model class (for example, from a getter).
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 static
Generate a new MongoDB ObjectId.
See also: description Converting types with Mondoc . -
objectIdToString(\MongoDB\BSON\ObjectId $id): string static
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 static
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 static
Deduplicates an array of MongoDB ObjectIds.
See also: description Converting types with Mondoc . -
arrayToPhp(mixed $item): mixed static
Converts an array to a PHP array. This method is useful when working with MongoDB
BSONArray, orBSONDocumentobjects.
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.
-
isDirty(string|null $property): bool
Determines if the model (pass
null), or a specific property, is dirty. The argument is required. 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 protected
Protected: only callable from inside your model class, for example from a setter.
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
addDirtymethod. Instead, Mondoc now establishes the dirty status by callingisDirtyorisDirtyFieldon the model. -
getMondocServiceClass(): string static
Retrieve the class name of the corresponding service to this model.
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' ];
Dirty tracking and introspection
Mondoc works out which fields have changed by comparing the model's current values with the original
BSON document it was loaded from. Only those fields are sent in the $set of an update. The
following public methods let you inspect, and in some cases influence, that state.
-
getDirty(): array
Returns the names of the properties that will be written on the next update. This includes fields added with
addDirty, fields whose value differs from the original BSON document, and changed unmapped fields. -
clearDirty(): static
Clears the list of fields that were explicitly marked dirty with
addDirty. It does not reset changes detected by comparing against the original BSON document. The service calls it after a successful insert or update. -
getOriginalBsonDocument(): ?\MongoDB\Model\BSONDocument
Returns the BSON document the model was loaded from (or the document written on the last insert), or
nullfor a model that has never been loaded or saved. This is the baseline used for dirty checking. -
getUnmappedFields(): array
Returns any key/value pairs from the document that didn't match a property on the model. These are kept and written back when the model is saved.
-
hasUnmappedProperties(): bool
Returns
trueif the document contained any fields not mapped to a model property. -
hasPresetObjectId(): bool
Returns
trueif a preset ObjectId has been set withsetPresetObjectId. -
getPresetObjectId(): ?\MongoDB\BSON\ObjectId
Returns the preset ObjectId, or
nullif none is set. -
clearPresetObjectId(): void
Removes the preset ObjectId. This is called automatically after a successful insert.
-
unsetObjectId(): static
Removes the model's ObjectId, so the next
save()performs an insert rather than an update. This is useful when cloning a document. -
isMondocFieldEncrypted(string $field): bool
Returns
trueif the given property name is listed in the model's$mondocEncryptedproperty. See field encryption. -
inflateSingleArray(array $data): static static
Creates a model instance from a PHP array of document data. If an
_idkey is present, it becomes the model's ObjectId. No original BSON document is set, so dirty checking has no baseline. -
inflateSingleBsonDocument(\MongoDB\Model\BSONDocument $document): static static
Creates a model instance from a
BSONDocumentand records that document as the original BSON document. This is what the service uses when loading documents.
Don't save a model loaded with a projection. If you pass a projection option
when loading a model, the projected-away fields are missing from the original BSON document. Their
properties keep their PHP defaults and, because the original document lacks those keys, they're treated
as changed. Saving the model can then overwrite real data with those defaults. Only save models that you
loaded in full.
A fully featured model
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 $this->addDirty('field')
from within the parent model (it's a protected method, so for example from a setter) 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.