diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 7e7e96206..0369cbb80 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -38,6 +38,7 @@ jobs: - name: "Add orphan metadata where needed" run: | printf '%s\n\n%s\n' ":orphan:" "$(cat docs/en/sidebar.rst)" > docs/en/sidebar.rst + printf '%s\n\n%s\n' ":orphan:" "$(cat docs/en/reference/attributes-reference.rst)" > docs/en/reference/attributes-reference.rst - name: "Run guides-cli" run: "docs/vendor/bin/guides -vvv --no-progress docs/en 2>&1 | grep -v 'No template found for rendering directive' | ( ! grep WARNING )" diff --git a/docs/en/cookbook/validation-of-documents.rst b/docs/en/cookbook/validation-of-documents.rst index c1f115932..d26220998 100644 --- a/docs/en/cookbook/validation-of-documents.rst +++ b/docs/en/cookbook/validation-of-documents.rst @@ -150,7 +150,7 @@ insertions and updates through a schema associated to the collection (cf. `MongoDB documentation `_). Doctrine MongoDB ODM provides a way to take advantage of this functionality -thanks to the :doc:`#[Validation] <../reference/annotations-reference#validation>` +thanks to the :doc:`#[Validation] <../reference/attributes-reference#validation>` attribute and its properties (also available with XML mapping): - @@ -251,5 +251,5 @@ the ``odm:schema:create`` or ``odm:schema:update`` command. -Please refer to the :doc:`#[Validation] <../reference/annotations-reference#document>` attributes reference +Please refer to the :doc:`#[Validation] <../reference/attributes-reference#document>` attributes reference for more details on how to use this feature. diff --git a/docs/en/reference/annotations-reference.rst b/docs/en/reference/annotations-reference.rst index 00e35ad6c..fa43fe9df 100644 --- a/docs/en/reference/annotations-reference.rst +++ b/docs/en/reference/annotations-reference.rst @@ -1,1336 +1,20 @@ Attributes Reference ===================== -In this chapter a reference of every Doctrine ODM Attribute is -given with short explanations on their context and usage. +Doctrine Annotations are deprecated and replaced by native PHP attributes. +All the attributes listed on :doc:`Attributes Reference ` +can be used as annotations. -#[AlsoLoad] ------------ +Support for annotations will be removed in Doctrine MongoDB ODM 3.0. -Specify one or more MongoDB fields to use for loading data if the original field -does not exist. +If you are still using annotations, you can migrate your code to attributes by +following the guide below: -.. code-block:: php - - firstName, $this->lastName) = explode(' ', $name); - } - } - -For additional information on using `#[AlsoLoad]`_, see -:doc:`Migrations `. - -#[ChangeTrackingPolicy] ------------------------ - -This attribute is used to change the change tracking policy for a document: - -.. code-block:: php - - `. - -#[DefaultDiscriminatorValue] ----------------------------- - -This attribute can be used when using `#[DiscriminatorField]`_. It will be used -as a fallback value if a document has no discriminator field set. This must -correspond to a value from the configured discriminator map. - -.. code-block:: php - - Person::class, 'employee' => Employee::class])] - #[DefaultDiscriminatorValue('person')] - class Person - { - // ... - } - -#[DiscriminatorField] ---------------------- - -This attribute is required for the top-most class in a -:ref:`single collection inheritance ` hierarchy. -It takes a string as its only argument, which specifies the database field to -store a class name or key (if a discriminator map is used). ODM uses this field -during hydration to select the instantiation class. - -.. code-block:: php - - ` hierarchy. -It takes an array as its only argument, which maps keys to class names. The -class names must be fully qualified. Using the ``::class constant`` is supported. When -a document is persisted to the database, its class name key will be stored in -the discriminator field instead of the |FQCN|. If the discriminator map is non-empty -and it does not contain the class name of the persisted document, a -``\Doctrine\ODM\MongoDB\Mapping\MappingException`` will be thrown. - -.. code-block:: php - - Person::class, 'employee' => Employee::class])] - class Person - { - // ... - } - -#[Document] ------------ - -Required attribute to mark a PHP class as a document, whose persistence will be -managed by ODM. - -Optional attributes: - -- - ``db`` - By default, the document manager will use the MongoDB database - defined in the configuration, but this option may be used to override the - database for a particular document class. -- - ``collection`` - By default, the collection name is derived from the - document's class name, but this option may be used to override that behavior. -- - ``repositoryClass`` - Specifies a custom repository class to use. -- - ``readOnly`` - Prevents document from being updated: it can only be inserted, - upserted or removed. -- - ``writeConcern`` - Specifies the write concern for this document that - overwrites the default write concern specified in the configuration. It does - not overwrite a write concern given as :ref:`option ` to the - ``flush`` method when committing your documents. - -.. code-block:: php - - 'desc'], options: ['unique' => true]) - ], - readOnly: true, - )] - class User - { - //... - } - -#[EmbedMany] ------------- - -This attribute is similar to `#[EmbedOne]`_, but instead of embedding one -document, it embeds a collection of documents. - -Optional attributes: - -- - ``targetDocument`` - A |FQCN| of the target document. -- - ``discriminatorField`` - The database field name to store the discriminator - value within the embedded document. -- - ``discriminatorMap`` - Map of discriminator values to class names. -- - ``defaultDiscriminatorValue`` - A default value for discriminatorField if no - value has been set in the embedded document. -- - ``strategy`` - The strategy used to persist changes to the collection. - Possible values are ``addToSet``, ``pushAll``, ``set``, and ``setArray``. - ``pushAll`` is the default. See :ref:`storage_strategies` for more - information. -- - ``collectionClass`` - A |FQCN| of class that implements ``Collection`` - interface and is used to hold documents. When typed properties - are used it is inherited from PHP type, otherwise Doctrine's ``ArrayCollection`` is - used by default. -- - ``notSaved`` - The property is loaded if it exists in the database; however, - ODM will not save the property value back to the database. - -.. code-block:: php - - Documents\BookTag::class, - 'song' => Documents\SongTag::class, - ], - defaultDiscriminatorValue: 'book', - )] - private $tags = []; - } - -Depending on the embedded document's class, a value of ``user`` or ``author`` -will be stored in the ``type`` field and used to reconstruct the proper class -during hydration. The ``type`` field need not be mapped on the embedded -document classes. - -#[EmbedOne] ------------ - -The `#[EmbedOne]`_ attribute works similarly to `#[ReferenceOne]`_, except that -that document will be embedded within the parent document. Consider the -following excerpt from the MongoDB documentation: - - The key question in MongoDB schema design is "does this object merit its own - collection, or rather should it be embedded within objects in other - collections?" In relational databases, each sub-item of interest typically - becomes a separate table (unless you are denormalizing for performance). In - MongoDB, this is not recommended – embedding objects is much more efficient. - Data is then collocated on disk; client-server turnarounds to the database - are eliminated. So in general, the question to ask is, "why would I not want - to embed this object?" - -Optional attributes: - -- - ``targetDocument`` - A |FQCN| of the target document. When typed properties - are used it is inherited from PHP type. -- - ``discriminatorField`` - The database field name to store the discriminator - value within the embedded document. -- - ``discriminatorMap`` - Map of discriminator values to class names. -- - ``defaultDiscriminatorValue`` - A default value for discriminatorField if no - value has been set in the embedded document. -- - ``notSaved`` - The property is loaded if it exists in the database; however, - ODM will not save the property value back to the database. - -.. code-block:: php - - Documents\User::class, - 'author' => Documents\Author::class, - ], - defaultDiscriminatorValue: 'user', - )] - private $creator; - } - -Depending on the embedded document's class, a value of ``user`` or ``author`` -will be stored in the ``type`` field and used to reconstruct the proper class -during hydration. The ``type`` field need not be mapped on the embedded -document classes. - -#[EmbeddedDocument] -------------------- - -Marks the document as embeddable. This attribute is required for any documents -to be stored within an `#[EmbedOne]`_, `#[EmbedMany]`_ or `#[File\\Metadata]`_ -relationship. - -.. code-block:: php - - amount = $amount; - } - //... - } - - #[Document(db: 'finance', collection: 'wallets')] - class Wallet - { - #[EmbedOne(targetDocument: Money::class)] - private $money; - - public function setMoney(Money $money): void - { - $this->money = $money; - } - //... - } - //... - $wallet = new Wallet(); - $wallet->setMoney(new Money(34.39)); - $dm->persist($wallet); - $dm->flush(); - -Unlike normal documents, embedded documents cannot specify their own database or -collection. That said, a single embedded document class may be used with -multiple document classes, and even other embedded documents! - -#[Field] --------- - -Marks an annotated instance variable for persistence. Values for this field will -be saved to and loaded from the document store as part of the document class' -lifecycle. - -Optional attributes: - -- - ``type`` - Name of the ODM type, which will determine the value's - representation in PHP and BSON (i.e. MongoDB). See - :ref:`doctrine_mapping_types` for a list of types. Defaults to "string" or - :ref:`Type from PHP property type `. -- - ``enumType`` - A |FQCN| of an ``enum``. ODM will automatically handle conversion - from the backing value stored in the database to an ``enum``. Can be auto-detected - by :ref:`type from PHP property type `. -- - ``name`` - By default, the property name is used for the field name in - MongoDB; however, this option may be used to specify a database field name. -- - ``nullable`` - By default, ODM will ``$unset`` fields in MongoDB if the PHP - value is null. Specify true for this option to force ODM to store a null - value in the database instead of unsetting the field. -- - ``notSaved`` - The property is loaded if it exists in the database; however, - ODM will not save the property value back to the database. - -Examples: - -.. code-block:: php - - ` attribute. - -.. code-block:: php - - `. - -The ``keys`` and ``options`` attributes correspond to the arguments for -`MongoDB\Collection::createIndex() `_. -ODM allows mapped field names (i.e. PHP property names) to be used when defining -``keys``. - -.. code-block:: php - - 'desc' ], options: ['unique' => true])] - class User - { - //... - } - -If you are creating a single-field index, you can simply specify an `#[Index]`_ or -`#[UniqueIndex]`_ on a mapped property: - -.. code-block:: php - - 'desc'], options: ['unique' => true]), - ])] - class User - { - //... - } - -#[InheritanceType] ------------------- - -This attribute must appear on the top-most class in an -:ref:`inheritance hierarchy `. ``SINGLE_COLLECTION`` and -``COLLECTION_PER_CLASS`` are currently supported. - -Examples: - -.. code-block:: php - - Person::class, 'employee' => Employee::class])] - class Person - { - // ... - } - -#[Lock] -------- - -The annotated instance variable will be used to store lock information for :ref:`pessimistic locking `. -This is only compatible with the ``int`` type, and cannot be combined with `#[Id]`_. - -.. code-block:: php - - ` for additional information. - -.. code-block:: php - - _` -that will be applied when querying for the annotated document. - -.. code-block:: php - - 'east' ], - [ 'dc' => 'west' ], - [] - ])] - class User - { - } - -.. _attributes_reference_reference_many: - -#[ReferenceMany] ----------------- - -Defines that the annotated instance variable holds a collection of referenced -documents. - -Optional attributes: - -- - ``targetDocument`` - A |FQCN| of the target document. A ``targetDocument`` - is required when using ``storeAs: id``. -- - ``storeAs`` - Indicates how to store the reference. ``id`` stores the - identifier, ``ref`` an embedded object containing the ``id`` field and - (optionally) a discriminator. ``dbRef`` and ``dbRefWithDb`` store a `DBRef`_ - object and are deprecated in favor of ``ref``. Note that ``id`` references - are not compatible with the discriminators. -- - ``cascade`` - Cascade Option -- - ``discriminatorField`` - The field name to store the discriminator value within - the reference object. -- - ``discriminatorMap`` - Map of discriminator values to class names. -- - ``defaultDiscriminatorValue`` - A default value for ``discriminatorField`` - if no value has been set in the referenced document. -- - ``inversedBy`` - The field name of the inverse side. Only allowed on owning side. -- - ``mappedBy`` - The field name of the owning side. Only allowed on the - inverse side. -- - ``repositoryMethod`` - The name of the repository method to call to populate - this reference. -- - ``sort`` - The default sort for the query that loads the reference. -- - ``criteria`` - Array of default criteria for the query that loads the - reference. -- - ``limit`` - Limit for the query that loads the reference. -- - ``skip`` - Skip for the query that loads the reference. -- - ``strategy`` - The strategy used to persist changes to the collection. - Possible values are ``addToSet``, ``pushAll``, ``set``, and ``setArray``. - ``pushAll`` is the default. See :ref:`storage_strategies` for more - information. -- - ``collectionClass`` - A |FQCN| of class that implements ``Collection`` - interface and is used to hold documents. When typed properties - are used it is inherited from PHP type, otherwise Doctrine's ``ArrayCollection`` is - used by default -- - ``prime`` - A list of references contained in the target document that will - be initialized when the collection is loaded. Only allowed for inverse - references. -- - ``notSaved`` - The property is loaded if it exists in the database; however, - ODM will not save the property value back to the database. - -.. code-block:: php - - 'asc'], - discriminatorField: 'type', - discriminatorMap: [ - 'book' => Documents\BookItem::class, - 'song' => Documents\SongItem::class, - ], - defaultDiscriminatorValue: 'book', - )] - private $cart; - } - -.. _attributes_reference_reference_one: - -#[ReferenceOne] ---------------- - -Defines an instance variable holds a related document instance. - -Optional attributes: - -- - ``targetDocument`` - A |FQCN| of the target document. A ``targetDocument`` - is required when using ``storeAs: id``. When typed properties are used - it is inherited from PHP type. -- - ``storeAs`` - Indicates how to store the reference. ``id`` stores the - identifier, ``ref`` an embedded object containing the ``id`` field and - (optionally) a discriminator. ``dbRef`` and ``dbRefWithDb`` store a `DBRef`_ - object and are deprecated in favor of ``ref``. Note that ``id`` references - are not compatible with the discriminators. -- - ``cascade`` - Cascade Option -- - ``discriminatorField`` - The field name to store the discriminator value - within the reference object. -- - ``discriminatorMap`` - Map of discriminator values to class names. -- - ``defaultDiscriminatorValue`` - A default value for ``discriminatorField`` - if no value has been set in the referenced document. -- - ``inversedBy`` - The field name of the inverse side. Only allowed on owning - side. -- - ``mappedBy`` - The field name of the owning side. Only allowed on the - inverse side. -- - ``repositoryMethod`` - The name of the repository method to call to populate - this reference. -- - ``sort`` - The default sort for the query that loads the reference. -- - ``criteria`` - Array of default criteria for the query that loads the - reference. -- - ``limit`` - Limit for the query that loads the reference. -- - ``skip`` - Skip for the query that loads the reference. -- - ``notSaved`` - The property is loaded if it exists in the database; however, - ODM will not save the property value back to the database. - -.. code-block:: php - - Documents\BookItem::class, - 'song' => Documents\SongItem::class, - ], - defaultDiscriminatorValue: 'book' - )] - private $cart; - } - -#[SearchIndex] --------------- - -This attribute is used to specify :ref:`search indexes ` for -`MongoDB Atlas Search `__. - -The attributes correspond to arguments for -`MongoDB\Collection::createSearchIndex() `__. -Excluding ``name``, attributes are used to create the -`search index definition `__. - -Optional attributes: - -- - ``name`` - Name of the search index to create, which must be unique to the - collection. Defaults to ``"default"``. -- - ``dynamic`` - Enables or disables dynamic field mapping for this index. - If ``true``, the index will include all fields with - `supported data types `__. - If ``false``, the ``fields`` attribute must be specified. Defaults to ``false``. -- - ``fields`` - Associative array of `field mappings `__ - that specify the fields to index (keys). Required only if dynamic mapping is disabled. -- - ``analyzer`` - Specifies the `analyzer `__ - to apply to string fields when indexing. Defaults to the - `standard analyzer `__. -- - ``searchAnalyzer`` - Specifies the `analyzer `__ - to apply to query text before the text is searched. Defaults to the - ``analyzer`` attribute, or the `standard analyzer `__. - if both are unspecified. -- - ``analyzers`` - Array of `custom analyzers `__ - to use in this index. -- - ``storedSource`` - Specifies document fields to store for queries performed - using the `returnedStoredSource `__ - option. Specify ``true`` to store all fields, ``false`` to store no fields, - or a `document `__ - to specify individual fields to include or exclude from storage. Defaults to ``false``. -- - ``synonyms`` - Array of `synonym mapping definitions `__ - to use in this index. - -.. note:: - - Search indexes have some notable differences from `#[Index]`_. They may only - be defined on document classes. Definitions will not be incorporated from - embedded documents. Additionally, ODM will **NOT** translate field names in - search index definitions. Database field names must be used instead of - mapped field names (i.e. PHP property names). - -#[ShardKey] ------------ - -This attribute may be used at the class level to specify a shard key to be used -for sharding the document collection. - -.. code-block:: php - - 'asc'])] - class User - { - //... - } - -#[UniqueIndex] --------------- - -Alias of `#[Index]`_, with the ``unique`` option set by default. - -.. code-block:: php - - `_ - for more details. The value should be a string representing a BSON document under the - `Extended JSON specification `_. - The recommended way to fill up this property is to create a class constant - (eg. ``::VALIDATOR``) using the - `HEREDOC/NOWDOC syntax `_ - for clarity and to reference it as the attribute value. -- - ``action`` - Determines how MongoDB handles documents that violate - the validation rules. Please refer to the related - `MongoDB documentation (Accept or Reject Invalid Documents ¶) `_ - for more details. The allowed values are the following: - - - ``error`` - - ``warn`` - - If it is not defined then the default behavior (``error``) will be used. - Those values are also declared as constants for convenience: - - - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_ERROR`` - - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_WARN`` - - Import the ``ClassMetadata`` namespace to use those constants in your attribute. -- - ``level`` - Determines which operations MongoDB applies the - validation rules. Please refer to the related - `MongoDB documentation (Existing Documents ¶) `_ - for more details. The allowed values are the following: - - - ``off`` - - ``strict`` - - ``moderate`` - - If it is not defined then the default behavior (``strict``) will be used. - Those values are also declared as constants for convenience: - - - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_OFF`` - - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_STRICT`` - - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_MODERATE`` - - Import the ``ClassMetadata`` namespace to use those constants in your attribute. - -.. code-block:: php - - `. -This is only compatible with types implementing the ``\Doctrine\ODM\MongoDB\Types\Versionable`` interface and cannot be -combined with `#[Id]`_. Following ODM types can be used for versioning: ``int``, ``decimal128``, ``date``, and -``date_immutable``. - -.. code-block:: php - - ` and -:ref:`reference-many ` collections in separate write operations, -which do not bump the document version. Users employing document versioning are -encouraged to use the :ref:`atomicSet ` or -:ref:`atomicSetArray ` strategies for such collections, which -will ensure that collections are updated in the same write operation as the -versioned parent document. - -#[View] -------- - -Required attribute to mark a PHP class as a view. Views are created from -aggregation pipelines, which are returned from a special repository method. -Views can be used like collections for any read operations. Result documents are -not managed and cannot be referenced using the :ref:`reference-many ` -and :ref:`reference-one ` mappings. - -Required attributes: - -- - ``rootClass`` - this is the base collection that the view is created from -- - ``repositoryClass`` - a repository class is required. This repository must - implement the ``MongoDB\ODM\MongoDB\Repository\ViewRepository`` interface. - -Optional attributes: - -- - ``db`` - By default, the document manager will use the MongoDB database - defined in the configuration, but this option may be used to override the - database for a particular document class. -- - ``view`` - By default, the view name is derived from the document's class - name, but this option may be used to override that behavior. - -.. code-block:: php - - project() - ->includeFields(['username']); - } - } - -The ``createViewAggregation`` method can add any aggregation pipeline stage, -except for the ``$out`` and ``$merge`` stages. The pipeline is created for the -root class specified in the view mapping. +Replace the `@ORM\Document` annotation with the `#[ORM\Document]` attribute. .. note:: - Views must be created before they can be queried. This can be done using the - ``odm:schema:create`` command. + You can use Rector to automate the migration process. See + `How to Upgrade Annotations to Attributes`_ for more information. -.. _BSON specification: http://bsonspec.org/spec.html -.. _DBRef: https://docs.mongodb.com/manual/reference/database-references/#dbrefs -.. _geoNear command: https://docs.mongodb.com/manual/reference/command/geoNear/ -.. _MongoDB\BSON\ObjectId: https://www.php.net/manual/en/class.mongodb-bson-objectid.php -.. |FQCN| raw:: html - FQCN +.. _How to Upgrade Annotations to Attributes: https://getrector.com/blog/how-to-upgrade-annotations-to-attributes diff --git a/docs/en/reference/attributes-reference.rst b/docs/en/reference/attributes-reference.rst new file mode 100644 index 000000000..00e35ad6c --- /dev/null +++ b/docs/en/reference/attributes-reference.rst @@ -0,0 +1,1336 @@ +Attributes Reference +===================== + +In this chapter a reference of every Doctrine ODM Attribute is +given with short explanations on their context and usage. + +#[AlsoLoad] +----------- + +Specify one or more MongoDB fields to use for loading data if the original field +does not exist. + +.. code-block:: php + + firstName, $this->lastName) = explode(' ', $name); + } + } + +For additional information on using `#[AlsoLoad]`_, see +:doc:`Migrations `. + +#[ChangeTrackingPolicy] +----------------------- + +This attribute is used to change the change tracking policy for a document: + +.. code-block:: php + + `. + +#[DefaultDiscriminatorValue] +---------------------------- + +This attribute can be used when using `#[DiscriminatorField]`_. It will be used +as a fallback value if a document has no discriminator field set. This must +correspond to a value from the configured discriminator map. + +.. code-block:: php + + Person::class, 'employee' => Employee::class])] + #[DefaultDiscriminatorValue('person')] + class Person + { + // ... + } + +#[DiscriminatorField] +--------------------- + +This attribute is required for the top-most class in a +:ref:`single collection inheritance ` hierarchy. +It takes a string as its only argument, which specifies the database field to +store a class name or key (if a discriminator map is used). ODM uses this field +during hydration to select the instantiation class. + +.. code-block:: php + + ` hierarchy. +It takes an array as its only argument, which maps keys to class names. The +class names must be fully qualified. Using the ``::class constant`` is supported. When +a document is persisted to the database, its class name key will be stored in +the discriminator field instead of the |FQCN|. If the discriminator map is non-empty +and it does not contain the class name of the persisted document, a +``\Doctrine\ODM\MongoDB\Mapping\MappingException`` will be thrown. + +.. code-block:: php + + Person::class, 'employee' => Employee::class])] + class Person + { + // ... + } + +#[Document] +----------- + +Required attribute to mark a PHP class as a document, whose persistence will be +managed by ODM. + +Optional attributes: + +- + ``db`` - By default, the document manager will use the MongoDB database + defined in the configuration, but this option may be used to override the + database for a particular document class. +- + ``collection`` - By default, the collection name is derived from the + document's class name, but this option may be used to override that behavior. +- + ``repositoryClass`` - Specifies a custom repository class to use. +- + ``readOnly`` - Prevents document from being updated: it can only be inserted, + upserted or removed. +- + ``writeConcern`` - Specifies the write concern for this document that + overwrites the default write concern specified in the configuration. It does + not overwrite a write concern given as :ref:`option ` to the + ``flush`` method when committing your documents. + +.. code-block:: php + + 'desc'], options: ['unique' => true]) + ], + readOnly: true, + )] + class User + { + //... + } + +#[EmbedMany] +------------ + +This attribute is similar to `#[EmbedOne]`_, but instead of embedding one +document, it embeds a collection of documents. + +Optional attributes: + +- + ``targetDocument`` - A |FQCN| of the target document. +- + ``discriminatorField`` - The database field name to store the discriminator + value within the embedded document. +- + ``discriminatorMap`` - Map of discriminator values to class names. +- + ``defaultDiscriminatorValue`` - A default value for discriminatorField if no + value has been set in the embedded document. +- + ``strategy`` - The strategy used to persist changes to the collection. + Possible values are ``addToSet``, ``pushAll``, ``set``, and ``setArray``. + ``pushAll`` is the default. See :ref:`storage_strategies` for more + information. +- + ``collectionClass`` - A |FQCN| of class that implements ``Collection`` + interface and is used to hold documents. When typed properties + are used it is inherited from PHP type, otherwise Doctrine's ``ArrayCollection`` is + used by default. +- + ``notSaved`` - The property is loaded if it exists in the database; however, + ODM will not save the property value back to the database. + +.. code-block:: php + + Documents\BookTag::class, + 'song' => Documents\SongTag::class, + ], + defaultDiscriminatorValue: 'book', + )] + private $tags = []; + } + +Depending on the embedded document's class, a value of ``user`` or ``author`` +will be stored in the ``type`` field and used to reconstruct the proper class +during hydration. The ``type`` field need not be mapped on the embedded +document classes. + +#[EmbedOne] +----------- + +The `#[EmbedOne]`_ attribute works similarly to `#[ReferenceOne]`_, except that +that document will be embedded within the parent document. Consider the +following excerpt from the MongoDB documentation: + + The key question in MongoDB schema design is "does this object merit its own + collection, or rather should it be embedded within objects in other + collections?" In relational databases, each sub-item of interest typically + becomes a separate table (unless you are denormalizing for performance). In + MongoDB, this is not recommended – embedding objects is much more efficient. + Data is then collocated on disk; client-server turnarounds to the database + are eliminated. So in general, the question to ask is, "why would I not want + to embed this object?" + +Optional attributes: + +- + ``targetDocument`` - A |FQCN| of the target document. When typed properties + are used it is inherited from PHP type. +- + ``discriminatorField`` - The database field name to store the discriminator + value within the embedded document. +- + ``discriminatorMap`` - Map of discriminator values to class names. +- + ``defaultDiscriminatorValue`` - A default value for discriminatorField if no + value has been set in the embedded document. +- + ``notSaved`` - The property is loaded if it exists in the database; however, + ODM will not save the property value back to the database. + +.. code-block:: php + + Documents\User::class, + 'author' => Documents\Author::class, + ], + defaultDiscriminatorValue: 'user', + )] + private $creator; + } + +Depending on the embedded document's class, a value of ``user`` or ``author`` +will be stored in the ``type`` field and used to reconstruct the proper class +during hydration. The ``type`` field need not be mapped on the embedded +document classes. + +#[EmbeddedDocument] +------------------- + +Marks the document as embeddable. This attribute is required for any documents +to be stored within an `#[EmbedOne]`_, `#[EmbedMany]`_ or `#[File\\Metadata]`_ +relationship. + +.. code-block:: php + + amount = $amount; + } + //... + } + + #[Document(db: 'finance', collection: 'wallets')] + class Wallet + { + #[EmbedOne(targetDocument: Money::class)] + private $money; + + public function setMoney(Money $money): void + { + $this->money = $money; + } + //... + } + //... + $wallet = new Wallet(); + $wallet->setMoney(new Money(34.39)); + $dm->persist($wallet); + $dm->flush(); + +Unlike normal documents, embedded documents cannot specify their own database or +collection. That said, a single embedded document class may be used with +multiple document classes, and even other embedded documents! + +#[Field] +-------- + +Marks an annotated instance variable for persistence. Values for this field will +be saved to and loaded from the document store as part of the document class' +lifecycle. + +Optional attributes: + +- + ``type`` - Name of the ODM type, which will determine the value's + representation in PHP and BSON (i.e. MongoDB). See + :ref:`doctrine_mapping_types` for a list of types. Defaults to "string" or + :ref:`Type from PHP property type `. +- + ``enumType`` - A |FQCN| of an ``enum``. ODM will automatically handle conversion + from the backing value stored in the database to an ``enum``. Can be auto-detected + by :ref:`type from PHP property type `. +- + ``name`` - By default, the property name is used for the field name in + MongoDB; however, this option may be used to specify a database field name. +- + ``nullable`` - By default, ODM will ``$unset`` fields in MongoDB if the PHP + value is null. Specify true for this option to force ODM to store a null + value in the database instead of unsetting the field. +- + ``notSaved`` - The property is loaded if it exists in the database; however, + ODM will not save the property value back to the database. + +Examples: + +.. code-block:: php + + ` attribute. + +.. code-block:: php + + `. + +The ``keys`` and ``options`` attributes correspond to the arguments for +`MongoDB\Collection::createIndex() `_. +ODM allows mapped field names (i.e. PHP property names) to be used when defining +``keys``. + +.. code-block:: php + + 'desc' ], options: ['unique' => true])] + class User + { + //... + } + +If you are creating a single-field index, you can simply specify an `#[Index]`_ or +`#[UniqueIndex]`_ on a mapped property: + +.. code-block:: php + + 'desc'], options: ['unique' => true]), + ])] + class User + { + //... + } + +#[InheritanceType] +------------------ + +This attribute must appear on the top-most class in an +:ref:`inheritance hierarchy `. ``SINGLE_COLLECTION`` and +``COLLECTION_PER_CLASS`` are currently supported. + +Examples: + +.. code-block:: php + + Person::class, 'employee' => Employee::class])] + class Person + { + // ... + } + +#[Lock] +------- + +The annotated instance variable will be used to store lock information for :ref:`pessimistic locking `. +This is only compatible with the ``int`` type, and cannot be combined with `#[Id]`_. + +.. code-block:: php + + ` for additional information. + +.. code-block:: php + + _` +that will be applied when querying for the annotated document. + +.. code-block:: php + + 'east' ], + [ 'dc' => 'west' ], + [] + ])] + class User + { + } + +.. _attributes_reference_reference_many: + +#[ReferenceMany] +---------------- + +Defines that the annotated instance variable holds a collection of referenced +documents. + +Optional attributes: + +- + ``targetDocument`` - A |FQCN| of the target document. A ``targetDocument`` + is required when using ``storeAs: id``. +- + ``storeAs`` - Indicates how to store the reference. ``id`` stores the + identifier, ``ref`` an embedded object containing the ``id`` field and + (optionally) a discriminator. ``dbRef`` and ``dbRefWithDb`` store a `DBRef`_ + object and are deprecated in favor of ``ref``. Note that ``id`` references + are not compatible with the discriminators. +- + ``cascade`` - Cascade Option +- + ``discriminatorField`` - The field name to store the discriminator value within + the reference object. +- + ``discriminatorMap`` - Map of discriminator values to class names. +- + ``defaultDiscriminatorValue`` - A default value for ``discriminatorField`` + if no value has been set in the referenced document. +- + ``inversedBy`` - The field name of the inverse side. Only allowed on owning side. +- + ``mappedBy`` - The field name of the owning side. Only allowed on the + inverse side. +- + ``repositoryMethod`` - The name of the repository method to call to populate + this reference. +- + ``sort`` - The default sort for the query that loads the reference. +- + ``criteria`` - Array of default criteria for the query that loads the + reference. +- + ``limit`` - Limit for the query that loads the reference. +- + ``skip`` - Skip for the query that loads the reference. +- + ``strategy`` - The strategy used to persist changes to the collection. + Possible values are ``addToSet``, ``pushAll``, ``set``, and ``setArray``. + ``pushAll`` is the default. See :ref:`storage_strategies` for more + information. +- + ``collectionClass`` - A |FQCN| of class that implements ``Collection`` + interface and is used to hold documents. When typed properties + are used it is inherited from PHP type, otherwise Doctrine's ``ArrayCollection`` is + used by default +- + ``prime`` - A list of references contained in the target document that will + be initialized when the collection is loaded. Only allowed for inverse + references. +- + ``notSaved`` - The property is loaded if it exists in the database; however, + ODM will not save the property value back to the database. + +.. code-block:: php + + 'asc'], + discriminatorField: 'type', + discriminatorMap: [ + 'book' => Documents\BookItem::class, + 'song' => Documents\SongItem::class, + ], + defaultDiscriminatorValue: 'book', + )] + private $cart; + } + +.. _attributes_reference_reference_one: + +#[ReferenceOne] +--------------- + +Defines an instance variable holds a related document instance. + +Optional attributes: + +- + ``targetDocument`` - A |FQCN| of the target document. A ``targetDocument`` + is required when using ``storeAs: id``. When typed properties are used + it is inherited from PHP type. +- + ``storeAs`` - Indicates how to store the reference. ``id`` stores the + identifier, ``ref`` an embedded object containing the ``id`` field and + (optionally) a discriminator. ``dbRef`` and ``dbRefWithDb`` store a `DBRef`_ + object and are deprecated in favor of ``ref``. Note that ``id`` references + are not compatible with the discriminators. +- + ``cascade`` - Cascade Option +- + ``discriminatorField`` - The field name to store the discriminator value + within the reference object. +- + ``discriminatorMap`` - Map of discriminator values to class names. +- + ``defaultDiscriminatorValue`` - A default value for ``discriminatorField`` + if no value has been set in the referenced document. +- + ``inversedBy`` - The field name of the inverse side. Only allowed on owning + side. +- + ``mappedBy`` - The field name of the owning side. Only allowed on the + inverse side. +- + ``repositoryMethod`` - The name of the repository method to call to populate + this reference. +- + ``sort`` - The default sort for the query that loads the reference. +- + ``criteria`` - Array of default criteria for the query that loads the + reference. +- + ``limit`` - Limit for the query that loads the reference. +- + ``skip`` - Skip for the query that loads the reference. +- + ``notSaved`` - The property is loaded if it exists in the database; however, + ODM will not save the property value back to the database. + +.. code-block:: php + + Documents\BookItem::class, + 'song' => Documents\SongItem::class, + ], + defaultDiscriminatorValue: 'book' + )] + private $cart; + } + +#[SearchIndex] +-------------- + +This attribute is used to specify :ref:`search indexes ` for +`MongoDB Atlas Search `__. + +The attributes correspond to arguments for +`MongoDB\Collection::createSearchIndex() `__. +Excluding ``name``, attributes are used to create the +`search index definition `__. + +Optional attributes: + +- + ``name`` - Name of the search index to create, which must be unique to the + collection. Defaults to ``"default"``. +- + ``dynamic`` - Enables or disables dynamic field mapping for this index. + If ``true``, the index will include all fields with + `supported data types `__. + If ``false``, the ``fields`` attribute must be specified. Defaults to ``false``. +- + ``fields`` - Associative array of `field mappings `__ + that specify the fields to index (keys). Required only if dynamic mapping is disabled. +- + ``analyzer`` - Specifies the `analyzer `__ + to apply to string fields when indexing. Defaults to the + `standard analyzer `__. +- + ``searchAnalyzer`` - Specifies the `analyzer `__ + to apply to query text before the text is searched. Defaults to the + ``analyzer`` attribute, or the `standard analyzer `__. + if both are unspecified. +- + ``analyzers`` - Array of `custom analyzers `__ + to use in this index. +- + ``storedSource`` - Specifies document fields to store for queries performed + using the `returnedStoredSource `__ + option. Specify ``true`` to store all fields, ``false`` to store no fields, + or a `document `__ + to specify individual fields to include or exclude from storage. Defaults to ``false``. +- + ``synonyms`` - Array of `synonym mapping definitions `__ + to use in this index. + +.. note:: + + Search indexes have some notable differences from `#[Index]`_. They may only + be defined on document classes. Definitions will not be incorporated from + embedded documents. Additionally, ODM will **NOT** translate field names in + search index definitions. Database field names must be used instead of + mapped field names (i.e. PHP property names). + +#[ShardKey] +----------- + +This attribute may be used at the class level to specify a shard key to be used +for sharding the document collection. + +.. code-block:: php + + 'asc'])] + class User + { + //... + } + +#[UniqueIndex] +-------------- + +Alias of `#[Index]`_, with the ``unique`` option set by default. + +.. code-block:: php + + `_ + for more details. The value should be a string representing a BSON document under the + `Extended JSON specification `_. + The recommended way to fill up this property is to create a class constant + (eg. ``::VALIDATOR``) using the + `HEREDOC/NOWDOC syntax `_ + for clarity and to reference it as the attribute value. +- + ``action`` - Determines how MongoDB handles documents that violate + the validation rules. Please refer to the related + `MongoDB documentation (Accept or Reject Invalid Documents ¶) `_ + for more details. The allowed values are the following: + + - ``error`` + - ``warn`` + + If it is not defined then the default behavior (``error``) will be used. + Those values are also declared as constants for convenience: + + - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_ERROR`` + - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_ACTION_WARN`` + + Import the ``ClassMetadata`` namespace to use those constants in your attribute. +- + ``level`` - Determines which operations MongoDB applies the + validation rules. Please refer to the related + `MongoDB documentation (Existing Documents ¶) `_ + for more details. The allowed values are the following: + + - ``off`` + - ``strict`` + - ``moderate`` + + If it is not defined then the default behavior (``strict``) will be used. + Those values are also declared as constants for convenience: + + - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_OFF`` + - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_STRICT`` + - ``\Doctrine\ODM\MongoDB\Mapping\ClassMetadata::SCHEMA_VALIDATION_LEVEL_MODERATE`` + + Import the ``ClassMetadata`` namespace to use those constants in your attribute. + +.. code-block:: php + + `. +This is only compatible with types implementing the ``\Doctrine\ODM\MongoDB\Types\Versionable`` interface and cannot be +combined with `#[Id]`_. Following ODM types can be used for versioning: ``int``, ``decimal128``, ``date``, and +``date_immutable``. + +.. code-block:: php + + ` and +:ref:`reference-many ` collections in separate write operations, +which do not bump the document version. Users employing document versioning are +encouraged to use the :ref:`atomicSet ` or +:ref:`atomicSetArray ` strategies for such collections, which +will ensure that collections are updated in the same write operation as the +versioned parent document. + +#[View] +------- + +Required attribute to mark a PHP class as a view. Views are created from +aggregation pipelines, which are returned from a special repository method. +Views can be used like collections for any read operations. Result documents are +not managed and cannot be referenced using the :ref:`reference-many ` +and :ref:`reference-one ` mappings. + +Required attributes: + +- + ``rootClass`` - this is the base collection that the view is created from +- + ``repositoryClass`` - a repository class is required. This repository must + implement the ``MongoDB\ODM\MongoDB\Repository\ViewRepository`` interface. + +Optional attributes: + +- + ``db`` - By default, the document manager will use the MongoDB database + defined in the configuration, but this option may be used to override the + database for a particular document class. +- + ``view`` - By default, the view name is derived from the document's class + name, but this option may be used to override that behavior. + +.. code-block:: php + + project() + ->includeFields(['username']); + } + } + +The ``createViewAggregation`` method can add any aggregation pipeline stage, +except for the ``$out`` and ``$merge`` stages. The pipeline is created for the +root class specified in the view mapping. + +.. note:: + + Views must be created before they can be queried. This can be done using the + ``odm:schema:create`` command. + +.. _BSON specification: http://bsonspec.org/spec.html +.. _DBRef: https://docs.mongodb.com/manual/reference/database-references/#dbrefs +.. _geoNear command: https://docs.mongodb.com/manual/reference/command/geoNear/ +.. _MongoDB\BSON\ObjectId: https://www.php.net/manual/en/class.mongodb-bson-objectid.php +.. |FQCN| raw:: html + FQCN diff --git a/docs/en/sidebar.rst b/docs/en/sidebar.rst index c89e4178a..13e3274c3 100644 --- a/docs/en/sidebar.rst +++ b/docs/en/sidebar.rst @@ -30,7 +30,7 @@ reference/trees reference/storing-files-with-gridfs reference/xml-mapping - reference/annotations-reference + reference/attributes-reference reference/metadata-drivers reference/working-with-objects reference/document-repositories