|
| 1 | +.. index:: |
| 2 | + single: Doctrine; Mapping Model classes |
| 3 | + |
| 4 | +How to provide model classes for several Doctrine implementations |
| 5 | +================================================================= |
| 6 | + |
| 7 | +When building a bundle that could be used not only with Doctrine ORM but |
| 8 | +also the CouchDB ODM, MongoDB ODM or PHPCR ODM, you should still only |
| 9 | +write one model class. The Doctrine bundles provide a compiler pass to |
| 10 | +register the mappings for your model classes. |
| 11 | + |
| 12 | +.. note:: |
| 13 | + |
| 14 | + For non-reusable bundles, the easiest is to put your model classes in |
| 15 | + the default locations. ``Entity`` for Doctrine ORM, ``Document`` for one |
| 16 | + of the ODMs. For reusable bundles, rather than duplicate model classes |
| 17 | + just to get the auto mapping, use the compiler pass. |
| 18 | + |
| 19 | +.. versionadded:: 2.3 |
| 20 | + The base mapping compiler pass was added in Symfony 2.3, the doctrine bundles |
| 21 | + support it from DoctrineBundle >= 1.2.1, MongoDBBundle >= 3.0.0 |
| 22 | + |
| 23 | + |
| 24 | +In your bundle class, write the following code to register the compiler pass:: |
| 25 | + |
| 26 | + use Doctrine\Bundle\DoctrineBundle\DependencyInjection\Compiler\DoctrineOrmMappingsPass; |
| 27 | + use Doctrine\Bundle\MongoDBBundle\DependencyInjection\Compiler\DoctrineMongoDBMappingsPass; |
| 28 | + |
| 29 | + class FOSUserBundle extends Bundle |
| 30 | + { |
| 31 | + public function build(ContainerBuilder $container) |
| 32 | + { |
| 33 | + parent::build($container); |
| 34 | + // ... |
| 35 | + |
| 36 | + $modelDir = realpath(__DIR__.'/Resources/config/doctrine/model'); |
| 37 | + $mappings = array( |
| 38 | + $modelDir => 'FOS\UserBundle\Model', |
| 39 | + ); |
| 40 | + |
| 41 | + $ormCompilerClass = 'Doctrine\Bundle\DoctrineBundle\DependencyInjection' |
| 42 | + . '\Compiler\DoctrineOrmMappingsPass'; |
| 43 | + if (class_exists($ormCompilerClass)) { |
| 44 | + $container->addCompilerPass( |
| 45 | + DoctrineOrmMappingsPass::createXmlMappingDriver( |
| 46 | + $mappings, 'fos_user.backend_type_orm' |
| 47 | + )); |
| 48 | + } |
| 49 | + |
| 50 | + $mongoCompilerClass = 'Doctrine\Bundle\MongoDBBundle\DependencyInjection' |
| 51 | + . '\Compiler\DoctrineMongoDBMappingsPass'; |
| 52 | + if (class_exists($mongoCompilerClass)) { |
| 53 | + $container->addCompilerPass( |
| 54 | + DoctrineMongoDBMappingsPass::createXmlMappingDriver( |
| 55 | + $mappings, 'fos_user.backend_type_mongodb' |
| 56 | + )); |
| 57 | + } |
| 58 | + |
| 59 | + // TODO: couch |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | +The compiler pass provides factory methods for all drivers provided by the |
| 64 | +bundle: Annotations, XML, Yaml, PHP and StaticPHP for Doctrine ORM, the ODM |
| 65 | +bundles sometimes do not have all of those drivers. |
0 commit comments