18 KiB
UPGRADE FROM 1.x to 2.0
PHP requirements
- MongoDB ODM 2.0 requires PHP 7.2 or newer. If you're not running PHP 7.2 yet,
it's recommended that you upgrade to PHP 7.2 before upgrading ODM. You can use
alcaeus/mongo-php-adapterto use ODM 1.x with PHP 7. - Most methods have been updated to include type hints where applicable. Please check your extension points to make sure the function signatures are correct.
- All files in ODM 2.0 use strict typing. Please make sure to not rely on type coercion.
MongoDB driver change
- MongoDB ODM 2.0 now requires the new MongoDB extension,
ext-mongodb. If you've been usingalcaeus/mongo-php-adapteryou can remove it completely and use ODM 2.0 directly. doctrine/mongodbis no longer used by ODM. If you've been relying on its functionality, please update accordingly. Most utility classes fromdoctrine/mongodbhave been merged into their ODM counterparts. Classes handling connections to MongoDB servers are being replaced by the MongoDB library (mongodb/mongodb).- The constructor signature of
Doctrine\ODM\MongoDB\DocumentManageras well as thecreate,getClient,getDocumentDatabase,getDocumentCollection, andgetDocumentCollectionsmethods have been updated to handle classes frommongodb/mongodbinstead ofdoctrine/mongodb.
Commands
- The
--depthoption in theodm:querycommand was dropped without replacement. - The
--timeoutoption for all schema commands was dropped. You should use the--maxTimeMsoption instead.
Aggregation builder
- The
debugmethod inDoctrine\ODM\MongoDB\Aggregation\Stage\Matchwas dropped without replacement.
Configuration
- The
setDefaultRepositoryClassNameandgetDefaultRepositoryClassNamemethods inDoctrine\ODM\MongoDB\Configurationhave been renamed tosetDefaultDocumentRepositoryClassNameandgetDefaultDocumentRepositoryClassNamerespectively. - The
setAutoGenerateProxyClassesandsetAutoGenerateHydratorClassesmethods no longer acceptboolarguments. Use one of theAUTOGENERATE_*constants from theConfigurationclass instead. - The
setRetryConnectandsetRetryQuerymethods have been dropped without replacement. You should implement proper error handling instead of simply re-running queries or connection attempts. - The
AUTOGENERATE_ALWAYSandAUTOGENERATE_NEVERgeneration strategies for proxy objects have been removed. UseAUTOGENERATE_EVALandAUTOGENERATE_FILE_NOT_EXISTSinstead. This does not affect hydrator or collection generation strategies.
Cursor changes
- Methods that previously returned a
MongoCursorinstance no longer return a cursor directly but rather compose the cursor in iterators implementing theDoctrine\ODM\MongoDB\Iterator\Iteratorinterface. This class provides atoArraymethod in addition to the methods provided in PHP core'sIteratorinterface. - The
Doctrine\ODM\MongoDB\Cursor,Doctrine\ODM\MongoDB\EagerCursor, andDoctrine\ODM\MongoDB\CommandCursorclasses has been dropped without replacement. You should always use the iterator interface mentioned above in type hints.
Document manager
- The
flushmethod inDoctrine\ODM\MongoDB\DocumentManagerno longer takes a$documentas its first argument. Flushing single documents has been removed. If you don't want to implicitly flush changes in all documents to the database, consider using a different changeset computation strategy (e.g. explicit). - The
createDBRefmethod has been dropped in favor ofcreateReference. This new method handles the creation of different kinds of references, not onlyDBRef. - The
$idargument inDoctrine\ODM\MongoDB\DocumentPersister::refreshhas been dropped as it was never used.
GridFS
GridFS support has been adapted to the new GridFS specification. The following are no longer possible:
- Metadata must be stored in a
metadataembedded document. Storing additional metadata in the root document is no longer supported. If you have documents that store metadata in the root document, migrate those documents to the new format. - New files are no longer persisted by flushing the DocumentManager. Instead,
they are uploaded using special methods in the new
Doctrine\ODM\MongoDB\Repository\GridFSRepositoryclass. - The mapping of GridFS files has changed significantly: GridFS files are no longer mapped as documents but as files and there are specific annotations for the GridFS metadata fields.
- The file's binary data can be downloaded by using special methods in the
Doctrine\ODM\MongoDB\Repository\GridFSRepositoryclass. It is no longer directly accessible from the document.
Mapping
General mapping changes
- The
Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfoclass was dropped and its functionality integrated intoDoctrine\ODM\MongoDB\Mapping\ClassMetadata. - The
safeoption for index creation has been dropped without replacement as this is no longer applicable to current versions of MongoDB. - Combining
repositoryMethodwithsortorlimitoptions on inverse references is no longer supported due to changes in the MongoDB driver. - Repository methods used with
repositoryMethodin inverse references now have to return an iterator of typeDoctrine\ODM\MongoDB\Iterator\Iteratorinstead of a cursor. - References use
dbrefas the default type when storing references instead ofdbRefWithDB. This omits the$dbkey in theDBRefobject when possible. This only has implications if you consume documents outside of ODM and require the$dbkey to be set or if you are using multiple databases to store data. - The
dropDupsoption on indexes has been dropped without replacement since it is no longer respected by MongoDB.
YAML mapping
The YAML mapping drivers have been removed. Please map your documents using XML or annotations. To migrate away from YAML mappings, first update to MongoDB ODM 1.3 and convert your mappings using the provided command.
XML mapping
- The XML driver validates the schema before applying the mapping. If your XML mapping file is invalid, ODM will not load it and throw an exception.
- Most mapping types now use
choiceinstead ofsequence, allowing you to map your documents in the order you prefer. - The
writeConcernattribute in thedocumentelement has been renamed towrite-concernfor consistency with other attributes. - The
require-indexesattribute in thedocumentelement has been dropped without replacement. - The
slave-okayattribute in thedocumentelement has been dropped. Use theread-preferenceelement for more fine-grained read control. - The
fieldelement no longer supports mapping identifiers. Use theidelement instead. Theidandid-generator-optionsattributes offieldhave been dropped in the process. - The
fileattribute offieldhas been dropped. More information on this is available in the GridFS update chapter. - The
distanceattribute offieldhas been dropped without replacement. If you've been usinggeoNearqueries, you should refactor them to use the aggregation framework and$geoNearpipeline operator. - The
fieldNameattribute of thefield,embed-one,embed-many,reference-one, andreference-manyelements has been renamed tofield-namefor consistency. - The
field,embed-one,embed-many,reference-one, andreference-manyelements now support thenot-saved,nullable, andalso-loadmapping options. - The
strategyattribute forembed-oneandreference-onehas been dropped. It was never used and does not apply to single-document relationships. - The
cascadeelement for documents now supports cascadingdetachoperations to related documents. - The
safeattribute ofindexhas been dropped without replacement.
Annotation mapping
- Combining
@Document,@EmbeddedDocument,@File,@MappedSuperclassand@QueryResultDocumentannotations on a single class will result in aMappingException. - The
$safeproperty in the@Indexand@UniqueIndesxannotations has been dropped without replacement. - The following annotation classes have been dropped in favor of specifying the
typeattribute in theFieldannotation:Bin,BinCustom,BinFunc,BinMD5,BinUUID,BinUUIDRFC4122,Bool,Boolean,Collection,Date,Float,Hash,Increment,Int,Integer,Key,ObjectId,Raw,String,Timestamp. - The
NotSavedannotation has been dropped in favor of thenotSavedattribute on theFieldannotation. ThenotSavedattribute can also be applied to reference and embed mappings. - The
$nameand$fieldNameproperties in theDiscriminatorFieldannotation class have been dropped. The field name is now passed via the default$valueproperty. - The
Distanceannotation class has been dropped without replacement. If you've been usinggeoNearqueries, you should refactor them to use the aggregation framework and$geoNearpipeline operator. - The
DoctrineAnnotations.phploader has been removed. You should register a class loader in theAnnotationRegistryinstead if you are using the ODM without a framework integration (e.g.doctrine/mongodb-odm-bundle). - The
requireIndexesoption in theDocumentannotation has been dropped without replacement. - The
slaveOkayoption in theDocumentannotation has been dropped. Use aReadPreferenceannotation for more fine-grained read control. - The
Fileannotation class is no longer a field-level annotation but now used on a class. More information on this is available in the GridFS update chapter. - The
simpleoption forReferenceOneandReferenceManyannotations has been dropped. Use thestoreAsoption with an appropriate value instead. - The
registerAnnotationClassesmethod inDoctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriverhas been dropped without replacement. You should register a class loader in theAnnotationRegistryinstead.
Same-namespace resolution dropped
With same-namespace resolution, the metadata driver would look for a class of
that name in the same namespace if the given class name didn't contain a
namespace separator (\). This is no longer supported, use fully qualified
class names or the ::class constant instead:
/**
* @ODM\Document(repositoryClass=UserRepository::class)
*/
class User
{
/**
* @ODM\ReferenceMany(targetDocument=Group::class)
*/
private $groups;
}
This affects the repositoryClass attribute in documents, targetDocument in
references and embedded relationships as well as class names in discriminator
maps.
Proxy objects
The proxy implementation no longer relies on Doctrine proxies but rather the Proxy Manager library by ocramius. If you are checking for proxies, the following changed:
- Proxies no longer implement
Doctrine\ODM\MongoDB\Proxy\Proxyor any other Doctrine proxy interface. To check whether a returned object is a proxy, check for theProxyManager\Proxy\GhostObjectInterfaceinterface. - The
__loadmethod has been replaced byinitializeProxy. - The
__isInitializedmethod has been replaced byisProxyInitialized. - To resolve the original class name for a proxy object, you can no longer use
the
Doctrine\Common\Util\ClassUtilsclass. Instead, fetch the class name resolver from the document manager:$dm->getClassNameResolver()->getRealClass($className); - The return value of the
getClassNameResolvermethod was updated in 2.0.0. The previously returnedDoctrine\ODM\MongoDB\Proxy\ClassNameResolverclass was dropped in favour of theDoctrine\ODM\MongoDB\Proxy\Resolver\ClassNameResolverinterface. This BC break was necessary to mitigate a performance regression. ThegetClassmethod was dropped from the interface as it wasn't being used.
Repository
- The
Doctrine\ODM\MongoDB\DocumentRepositoryclass has been renamed toDoctrine\ODM\MongoDB\Repository\DocumentRepository. - The
findBy*andfindOneBy*magic methods have been dropped. Please create explicit methods or use thefindByandfindOneBymethods instead. - The
Doctrine\ODM\MongoDB\Repository\DefaultRepositoryFactoryclass has been madefinal.
Query
- The
requireIndexesmethod inDoctrine\ODM\MongoDB\Query\Builderhas been dropped without replacement. If you want to require indexes for queries, use thenotablescanoption in the MongoDB server. - Running
geoNearcommands through thegeoNearhelper in the query builder is no longer supported. Please refactor your queries to use the aggregation framework and$geoNearpipeline operator. - Running
groupandmapReducecommands through the query builder is no longer supported. Please either refactor your queries to use the aggregation framework or use the MongoDB library (mongodb/mongodb) to execute these commands. - The
Doctrine\ODM\MongoDB\Query\FieldExtractorclass was dropped entirely. - The
getIteratormethod inDoctrine\ODM\MongoDB\Query\Queryreturns an iterator of typeDoctrine\ODM\MongoDB\Iterator\Iteratorinstead of a MongoDB cursor. - The
executemethod inDoctrine\ODM\MongoDB\Query\Querynow returns an iterator of typeDoctrine\ODM\MongoDB\Iterator\Iteratorfor find queries, and a plain array for distinct queries. - The
eagerCursorhelper inDoctrine\ODM\MongoDB\Query\Builderand its logic have been removed entirely without replacement. - Querying for a mapped superclass in a complex inheritance chain will now only return children of that specific class instead of all classes in the inheritance tree.
Schema manager
- The schema manager no longer implicitly creates indexes covering the shard key when sharding a collection. While MongoDB creates this index automatically when sharding an empty collection, it is recommended users explicitly map an index covering the shard key.
- The
createDatabasesandcreateDocumentDatabasesmethods have been removed fromDoctrine\ODM\MongoDB\SchemaManager. Databases are created implicitly in MongoDB 3.0. - The
--dbargument to theodm:schema:createconsole command has been removed.
Tools
- The
Doctrine\ODM\MongoDB\Tools\DisconnectedClassMetadataFactoryclass has been dropped without replacement. - Document and repository generation was removed completely.
Types
- The
Doctrine\ODM\MongoDB\Types\FileTypeclass was removed completely. - The
Doctrine\ODM\MongoDB\Types\IncrementTypeclass was removed completely. Use anincrementstrategy on the field mapping forintandfloatfields instead.
Unit of work
- The
commitmethod inDoctrine\ODM\MongoDB\UnitOfWorkno longer takes a$documentas its first argument. Flushing single documents has been removed. If you don't want to implicitly flush changes in all documents to the database, consider using a different changeset computation strategy (e.g. explicit). - Triggering a
commitwhile one is already in progress will now cause an exception. This would usually happen if you flushed the document manager from within a lifecycle event handler. Since data integrity can't be guaranteed, it is no longer allowed to nest flushes to the database. - The
isScheduledForDirtyCheckandscheduleForDirtyCheckmethods have been renamed toisScheduledForSynchronizationandscheduleForSynchronization, respectively.
Internal classes and methods
Number of public methods and classes saw an @internal annotation added. This
marks places which are considered private to ODM but can not become ones due to
language limitations. Those methods can still be used (at your own risk) however
the backward compatibility promise for them is relaxed: we reserve the right to
change internal method's signatures and/or remove them altogether in minor
releases. Should such change be made, a note shall be included in the UPGRADE.md
file describing changes contained in the release.
Final classes
Following classes have been made final:
Doctrine\ODM\MongoDB\DocumentNotFoundExceptionDoctrine\ODM\MongoDB\Event\DocumentNotFoundEventArgsDoctrine\ODM\MongoDB\Event\LoadClassMetadataEventArgsDoctrine\ODM\MongoDB\Event\OnClassMetadataNotFoundEventArgsDoctrine\ODM\MongoDB\Event\OnClearEventArgsDoctrine\ODM\MongoDB\Event\OnFlushEventArgsDoctrine\ODM\MongoDB\Event\PostCollectionLoadEventArgsDoctrine\ODM\MongoDB\Event\PostFlushEventArgsDoctrine\ODM\MongoDB\Event\PreFlushEventArgsDoctrine\ODM\MongoDB\Event\PreLoadEventArgsDoctrine\ODM\MongoDB\Event\PreUpdateEventArgsDoctrine\ODM\MongoDB\Hydrator\HydratorExceptionDoctrine\ODM\MongoDB\Hydrator\HydratorFactoryDoctrine\ODM\MongoDB\Id\AlnumGeneratorDoctrine\ODM\MongoDB\Id\AutoGeneratorDoctrine\ODM\MongoDB\Id\IncrementGeneratorDoctrine\ODM\MongoDB\Id\UuidGeneratorDoctrine\ODM\MongoDB\LockExceptionDoctrine\ODM\MongoDB\LockModeDoctrine\ODM\MongoDB\Mapping\ClassMetadataFactoryDoctrine\ODM\MongoDB\Mapping\MappingExceptionDoctrine\ODM\MongoDB\PersistentCollectionDoctrine\ODM\MongoDB\PersistentCollection\PersistentCollectionExceptionDoctrine\ODM\MongoDB\Persisters\CollectionPersisterDoctrine\ODM\MongoDB\Persisters\DocumentPersisterDoctrine\ODM\MongoDB\Persisters\PersistenceBuilderDoctrine\ODM\MongoDB\Proxy\Factory\StaticProxyFactoryDoctrine\ODM\MongoDB\Query\CriteriaMergerDoctrine\ODM\MongoDB\Query\FilterCollectionDoctrine\ODM\MongoDB\Query\QueryDoctrine\ODM\MongoDB\Query\QueryExpressionVisitorDoctrine\ODM\MongoDB\Query\ReferencePrimerDoctrine\ODM\MongoDB\SchemaManagerDoctrine\ODM\MongoDB\UnitOfWorkDoctrine\ODM\MongoDB\Utility\CollectionHelperDoctrine\ODM\MongoDB\Utility\LifecycleEventManager