Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

233 lines (159 sloc) 6.121 kB

Mapping Classes to the ORM and ODM

Because of the non intrusive design of Doctrine it is possible for you to have plain PHP classes that are mapped to both a relational database with the Doctrine2 Object Relational Mapper and MongoDB with the Doctrine MongoDB Object Document Mapper, or any other persistence layer that implements the Doctrine Common persistence interfaces.

Test Subject

For this cookbook entry we need to define a class that can be persisted to both MySQL and MongoDB. We'll use a BlogPost as you may want to write some generic blogging functionality that has support for multiple Doctrine persistence layers:

<?php

namespace Doctrine\Blog;

class BlogPost
{
    private $id;
    private $title;
    private $body;

    // ...
}

Mapping Information

Now we just need to provide the mapping information for the Doctrine persistence layers so they know how to consume the objects and persist them to the database.

ORM

First define the mapping for the ORM:

Now you are able to persist the Documents\BlogPost with an instance of EntityManager:

<?php

$blogPost = new BlogPost()
$blogPost->setTitle('test');

$em->persist($blogPost);
$em->flush();

You can find the blog post:

<?php

$blogPost = $em->getRepository('Documents\BlogPost')->findOneByTitle('test');

MongoDB ODM

Now map the same class to the Doctrine MongoDB ODM:

Now the same class is able to be persisted in the same way using an instance of DocumentManager:

<?php

$blogPost = new BlogPost()
$blogPost->setTitle('test');

$dm->persist($blogPost);
$dm->flush();

You can find the blog post:

<?php

$blogPost = $dm->getRepository('Documents\BlogPost')->findOneByTitle('test');

Repository Classes

You can implement the same repository interface for the ORM and MongoDB ODM easily:

<?php

namespace Doctrine\Blog\ORM;

use Doctrine\ORM\EntityRepository;

class BlogPostRepository extends EntityRepository
{
    public function findPostById($id)
    {
        return $this->findOneBy(array('id' => $id));
    }
}

Now define the same repository methods for the MongoDB ODM:

<?php

namespace Doctrine\Blog\ODM\MongoDB;

use Doctrine\ODM\MongoDB\DocumentRepository;

class BlogPostRepository extends DocumentRepository
{
    public function findPostById($id)
    {
        return $this->findOneBy(array('id' => $id));
    }
}

As you can see the repositories are the same and the final returned data is the same vanilla PHP objects. The data is transparently injected to the objects for you automatically so you are not forced to extend some base class or shape your domain in any certain way for it to work with the Doctrine persistence layers.

Jump to Line
Something went wrong with that request. Please try again.