SlideShare a Scribd company logo
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                           Doctrine
               MongoDB Object Document Mapper (ODM)




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                  What is Doctrine?



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                  What is Doctrine?
ā€¢   Open source PHP project started in 2006

ā€¢   Relational database abstraction layer.
      ā€¢       mysql, oracle, pgsql, sqlite, etc.



ā€¢   Object persistence layers for RDBMS,
    MongoDB, etc.

ā€¢   Other database related functionalities.
                               http://www.doctrine-project.org
                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




               What is MongoDB?
ā€¢   Key-Value document based storage
    system.

ā€¢   Bridge between traditional relational
    databases and key-value data stores.



                               http://www.mongodb.org

                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                #sfdaycgn




                                  Terminology

                        RDBMS                                        MongoDB
                            Database                                        Database

                               Table                                       Collection

                                Row                                        Document




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




    Using MongoDB in PHP



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                     Connecting


    $mongo = new Mongo('mongodb://localhost');




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




               Selecting Databases


    $mongo = new Mongo('mongodb://localhost');
    $db = $mongo->selectDB('dbname');




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




            Selecting Collections


    $mongo = new Mongo('mongodb://localhost');
    $db = $mongo->selectDB('dbname');
    $coll = $db->selectCollection('users');




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




           Inserting Documents
                   Insert a new user document and echo the newly generated id


    $user = array(
        'username' => 'jwage',
        'password' => md5('changeme')
        'active' => true
    );
    $coll->insert($user);

    echo $user['_id'];




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




           Updating Documents
                  Update username and password and save the whole document




    $user = $coll->findOne(array('username' => 'jwage'));
    $user['username'] = 'jonwage';
    $user['password'] = md5('newpassword');
    $coll->save($user);




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                        Atomic Updates
ā€¢   Faster than saving the entire document.

ā€¢   Safer than updating the entire document.

ā€¢   Updates are done in place and are atomic.




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                        Atomic Updates
                     Update username and password where username is jwage



    $coll->update(array(
        'username' => 'jwage'
    ), array(
        '$set' => array(
            'username' => 'jonwage',
            'password' => md5('newpassword')
        )
    ));




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                            Atomic Updates
                Many other atomic operators exist for manipulating a documents data




ā€¢       $inc - increments ļ¬eld by the number value
ā€¢       $set - sets ļ¬eld to value
ā€¢       $unset - deletes a given ļ¬eld
ā€¢       $push - appends value to an array
ā€¢       $pushAll - appends multiple values to an array
ā€¢       $addToSet - appends multiple values to an array that donā€™t already exist in the
        array
ā€¢       $pop - removes the last element in an array
ā€¢       $pull - removes all occurrences of a value from an array
ā€¢       $pullAll - removes all occurrences of multiple values from an array




                                         www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




        Removing Documents


    $coll->remove(array('username' => 'jwage'));




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




         Doctrine + MongoDB



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                DocumentManager
ā€¢   Abstraction on top of the PHP Mongo
    class

ā€¢   Manages the persistent state of PHP
    objects

ā€¢   Implements UnitOfWork for change
    tracking
                              http://martinfowler.com/eaaCatalog/unitOfWork.html

                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                         Document States
ā€¢      A NEW document instance has no persistent identity, and is not yet
       associated with a DocumentManager (i.e. those just created with the
       "new" operator).

ā€¢      A MANAGED document instance is an instance with a persistent
       identity that is associated with an DocumentManager and whose
       persistence is thus managed.

ā€¢      A DETACHED document instance is an instance with a persistent
       identity that is not (or no longer) associated with an
       DocumentManager.

ā€¢      A REMOVED document instance is an instance with a persistent
       identity, associated with an DocumentManager, that will be removed
       from the database upon transaction commit.


                                         www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                DocumentManager
         Create your DocumentManager instance for managing object persistence



    $config = new DoctrineODMMongoDBConfiguration();
    $config->setMetadataCacheImpl(new DoctrineCommonCacheArrayCache);
    $driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__."/Documents"));
    $config->setMetadataDriverImpl($driverImpl);

    $config->setProxyDir(__DIR__ . '/Proxies');
    $config->setProxyNamespace('Proxies');

    $dm = DoctrineORMDocumentManager::create($mongo, $config);




                                 Wraps around existing $mongo connection




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                             #sfdaycgn




               Deļ¬ning Document
                                  A document is just a regular oleā€™ PHP class

                                            class User
                                            {
                                                private $id;
                                                private $username;
                                                private $password;

                                                public function getId()
                                                {
                                                    return $this->id;
                                                }

                                                public function getUsername()
                                                {
                                                    return $this->username;
                                                }

                                                public function setUsername($username)
                                                {
                                                    $this->username = $username;
                                                }

                                                public function getPassword()
                                                {
                                                    return $this->password;
                                                }

                                                public function setPassword($password)
                                                {
                                                    $this->password = md5($password);
                                                }
                                            }




                                     www.doctrine-project.org                   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




    Mapping the Document
                                            /** @Document */
                                            class User
                                            {
                                                /** @Id */
                                                private $id;
                                                /** @String */
                                                private $username;
                                                /** @String */
                                                private $password;

                                                    // ...
                                            }




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                 Ready to Go
      Doctrine now knows about this document and is able
                 to manage its persistent state




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




      Inserting, Updating and
       Deleting Documents


                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                  #sfdaycgn




           Inserting Documents
                      $user = new User();
                      $user->setUsername('jwage');
                      $user->setPassword('changeme');

                      $dm->persist($user);
                      $dm->flush(); // inserts document




                                            $users = array(
                                                array(
                                                    'username' => 'jwage',
                                                    'password' => 'changeme'
                                                )
                                            );
                                            $coll->batchInsert($users);




                                     www.doctrine-project.org        www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




           Updating Documents
$user = $dm->findOne('User', array('username' => 'jwage'));

$user->setUsername('jonwage');
$user->setPassword('newpassword');

$dm->flush(); // updates document




                      $coll->update(
                          array('_id' => 'theid'),
                          array('$set' => array(
                              'username' => 'jonwage',
                              'password' => '5e9d11a14ad1c8dd77e98ef9b53fd1ba'
                          )
                      );




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




        Removing Documents

$user = $dm->findOne('User', array('username' => 'jwage'));

$dm->remove($user);
$dm->flush(); // removes document




                       $coll->remove(array('_id' => 'theid'));




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                       Query API
                                           Fluent OO Query API




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




             Querying MongoDB
                  Directly

// Get user array directly from mongo
$user = $mongo->db->users->findOne(array('username' => 'jwage'));




                         Returns an array of information and not a User object




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                   Querying Through
                      Doctrine

// Get user class instance through Doctrine
$user = $dm->findOne('User', array('username' => 'jwage'));




         Going through Doctrine gives you managed objects back instead of arrays




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




              Querying Through
             Doctrine Query API
// Get user class instance through Doctrine Query API
$user = $dm->createQuery('User')
    ->field('username')->equals('jwage')
    ->getSingleResult();




                                  Query for same user using the Query API




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




              Querying Through
             Doctrine Query API
               // Find posts within a range of dates
               $posts = $dm->createQuery('Post')
                   ->field('createdAt')->range($startDate, $endDate)
                   ->execute();




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




           Updating Documents

               // Update a document
               $dm->createQuery('User')
                   ->update()
                   ->field('username')->set('jonwage')
                   ->field('password')->set('newpassword')
                   ->field('username')->equals('jwage')
                   ->execute();




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




        Removing Documents

                // Remove a document
                $dm->createQuery('User')
                            // Remove a document
                            $dm->createQuery('User')

                    ->remove()  ->remove()
                                ->field('username')->equals('jwage')
                                ->execute();
                    ->field('username')->equals('jwage')
                    ->execute();




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




      Embedded Documents



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                  class User
                  {
                      /** @Id */
                      public $id;

                           /** @String */
                           public $name;

                           /** @EmbedMany(targetDocument="Address") */
                           public $addresses = array();
                  }




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                #sfdaycgn




                                           /** @EmbeddedDocument */
                                           class Address
                                           {
                                               /** @String */
                                               public $address;

                                                  /** @String */
                                                  public $city;

                                                  /** @String */
                                                  public $state;

                                                  /** @String */
                                                  public $zipcode;
                                           }




                                     www.doctrine-project.org      www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




             $user = new User();
             $user->name = 'Jonathan H. Wage';

             $address = new Address();
             $address->address = '6512 Mercomatic Ct';
             $address->city = 'Nashville';
             $address->state = 'Tennessee';
             $address->zipcode = '37209';
             $user->addresses[] = $address;

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




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




             $users = array(
                 array(
                     'name' => 'Jonathan H. Wage',
                     'addresses' => array(
                         array(
                             'address' => '6512 Mercomatic Ct',
                             'city' => 'Nashville',
                             'state' => 'Tennesseee',
                             'zipcode' => '37209'
                         )
                     )
                 )
             );
             $coll->batchInsert($users);




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




              Updating Embedded
                 Documents
       Uses dot notation and atomic operators for updating




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




             $user = $dm->findOne('User', array('name' => 'Jonathan H. Wage'));
             $user->addresses[0]->zipcode = '37205';
             $dm->flush();




             $coll->update(
                 array('_id' => 'theuserid'),
                 array('$set' => array('addresses.0.zipcode' => '37209'))
             );




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                   Add New Address



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




    $user = $dm->findOne('User', array('name' => 'Jonathan H. Wage'));

    $address = new Address();
    $address->address = '475 Buckhead Ave.';
    $address->city = 'Atlanta';
    $address->state = 'Georgia';
    $address->zipcode = '30305';
    $user->addresses[] = $address;

    $dm->flush();




                     $coll->update(
                         array('_id' => 'theuserid'),
                         array('$pushAll' => array(
                             'addresses' => array(
                                 array(
                                     'address' => '475 Buckhead Ave.',
                                     'city' => 'Atlanta',
                                     'state' => 'Georgia',
                                     'zipcode' => '30305'
                                 )
                             )
                         ))
                     );



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                    #sfdaycgn




    unset($user->addresses[0]->zipcode);
    $dm->flush();



                                 $coll->update(
                                     array('_id' => 'theuserid'),
                                     array(
                                         '$unset' => array(
                                             'addresses.0.zipcode'                   => 1
                                         )
                                     )
                                 );




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                      References
      MongoDB does not have joins or foreign keys but you
       can still store references to other documents and
        resolve the references in your application code.
      Doctrine abstracts the handling of referneces for you
                so working with them is seamless.




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                 #sfdaycgn




                                 Organization
                                 /** @Document */
                                 class Organization
                                 {
                                     /** @Id */
                                     private $id;

                                       /** @String */
                                       private $name;

                                       /** @ReferenceMany(targetDocument="User") */
                                       private $users = array();

                                       public function setName($name)
                                       {
                                           $this->name = $name;
                                       }

                                       public function addUser(User $user)
                                       {
                                           $this->users[] = $user;
                                       }
                                 }




                                     www.doctrine-project.org       www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                  #sfdaycgn




                                                      User
                       /** @Document */
                       class User
                       {
                           /** @Id */
                           private $id;

                            /** @String */
                            private $name;

                            /** @ReferenceOne(targetDocument="Organization") */
                            private $organization;

                            public function setName($name)
                            {
                                $this->name = $name;
                            }

                            public function setOrganization(Organization $organization)
                            {
                                $this->organization = $organization;
                                $organization->addUser($this);
                            }
                       }




                                     www.doctrine-project.org      www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                   $organization = new Organization();
                   $organization->setName('Sensio Labs');

                   $user = new User();
                   $user->setName('Jonathan H. Wage');
                   $user->setOrganization($organization);

                   $dm->persist($organization);
                   $dm->persist($user);
                   $dm->flush();




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                       The Result



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                    #sfdaycgn




                       Array
                       (
                           [_id] => 4c86acd78ead0e8759000000
                           [name] => Sensio Labs
                           [users] => Array
                               (
                                   [0] => Array
                                       (
                                            [$ref] => User
                                            [$id] => 4c86acd78ead0e8759010000
                                            [$db] => doctrine_odm_sandbox
                                       )

                                 )

                       )


                       Array
                       (
                           [_id] => 4c86acd78ead0e8759010000
                           [name] => Jonathan H. Wage
                           [organization] => Array
                               (
                                   [$ref] => Organization
                                   [$id] => 4c86acd78ead0e8759000000
                                   [$db] => doctrine_odm_sandbox
                               )

                       )




                                     www.doctrine-project.org          www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                               Working with
                                References



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




          $user = $dm->find('User', array('name' => 'Jonathan H. Wage'));

          // instance of uninitialized OrganizationProxy
          $organization = $user->getOrganization();

          // calling getter or setter for uninitialized proxy
          // queries the database and initialized the proxy document

          // query invoked, organization data loaded and doc initialized
          echo $organization->getName();




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




 $organization = $dm->find('Organization', array('name' => 'Sensio Labs'));
 $users = $organization->getUsers(); // uninitialized collection

 // Queries database for users and initializes collection
 foreach ($users as $user)
 {
     // ...
 }




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                        Change Tracking



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                 UnitOfWork
ā€¢   Tracks changes in objects between ļ¬‚ushes

ā€¢   Maintains copy of old values to compare
    new values to

ā€¢   Changesets computed and persisted in
    the most efļ¬cient way using atomic
    operators $inc, $set, $unset, $pullAll,
    $pushAll, etc.

                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                          Other Features



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                    Document Query
                       Language
       Language for querying documents in a similar way to
                              SQL




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                            BNF Grammar



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                                          #sfdaycgn


                 QueryLanguage ::= FindQuery | InsertQuery | UpdateQuery | RemoveQuery

                 FindQuery ::= FindClause [WhereClause] [MapClause] [ReduceClause] [SortClause] [LimitClause]
                 [SkipClause]
                 FindClause ::= "FIND" all | SelectField {"," SelectField}
                 SelectField ::= DocumentFieldName
                 SortClause ::= SortClauseField {"," SortClauseField}
                 SortClauseField ::= DocumentFieldName "ASC | DESC"
                 LimitClause ::= "LIMIT" LimitInteger
                 SkipClause ::= "SKIP" SkipInteger
                 MapClause ::= "MAP" MapFunction
                 ReduceClause ::= "REDUCE" ReduceFunction

                 DocumentFieldName ::= DocumentFieldName | EmbeddedDocument "." {"." DocumentFieldName}
                 WhereClause ::= "WHERE" WhereClausePart {"AND" WhereClausePart}
                 WhereClausePart ::= ["all", "not"] DocumentFieldName WhereClauseExpression Value
                 WhereClauseExpression ::= "=" | "!=" | ">=" | "<=" | ">" | "<" | "in"
                                         "notIn" | "all" | "size" | "exists" | "type"
                 Value ::= LiteralValue | JsonObject | JsonArray

                 UpdateQuery ::= UpdateClause [WhereClause]
                 UpdateClause ::= [SetExpression], [UnsetExpression], [IncrementExpression],
                                   [PushExpression], [PushAllExpression], [PullExpression],
                                   [PullAllExpression], [AddToSetExpression], [AddManyToSetExpression],
                                   [PopFirstExpression], [PopLastExpression]
                 SetExpression ::= "SET" DocumentFieldName "=" Value {"," SetExpression}
                 UnsetExpression ::= "UNSET" DocumentFieldName {"," UnsetExpression}
                 IncrementExpression ::= "INC" DocumentFieldName "=" IncrementInteger {"," IncrementExpression}
                 PushExpression ::= "PUSH" DocumentFieldName Value {"," PushExpression}
                 PushAllExpression ::= "PUSHALL" DocumentFieldName Value {"," PushAllExpression}
                 PullExpression ::= "PULL" DocumentFieldName Value {"," PullExpression}
                 PullAllExpression ::= "PULLALL" DocumentFieldName Value {"," PullAllExpression}
                 AddToSetExpression ::= "ADDTOSET" DocumentFieldName Value {"," AddToSetExpression}
                 AddManyToSetExpression ::= "ADDMANYTOSET" DocumentFieldName Value {"," AddManyToSetExpression}
                 PopFirstExpression ::= "POPFIRST" DocumentFieldName {"," PopFirstExpression}
                 PopLastExpression ::= "POPLAST" DocumentFieldName {"," PopLastExpression}

                 InsertQuery ::= InsertClause InsertSetClause {"," InsertSetClause}
                 InsertSetClause ::= DocumentFieldName "=" Value

                 RemoveQuery ::= RemoveClause [WhereClause]




                                     www.doctrine-project.org                 www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                         Creating Query


                  $users = $dm->query('find all FROM User');




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                           Selecting Fields


            $users = $dm->query('find username FROM User');




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                              Paging Results


   $users = $dm->query('find all FROM User limit 30 skip 30');




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




         Selecting Slice of
       Embedded Documents

$post = $dm->query('find title, comments limit 20 skip 10 FROM
BlogPost WHERE id = ?', array($id));




                                      www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                           Other Examples
// Find all posts greater than or equal to a date
$posts = $dm->query('find all FROM BlogPost WHERE createdAt >= ?',
array($date));

// Find all posts sorted by created at desc
$posts = $dm->query('find all FROM BlogPost sort createdAt desc');

// Update user
$dm->query('update DocumentsUser set password = ? where username = ?',
array('newpassword', 'jwage'));




                                        www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                          Lifecycle Events



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                    #sfdaycgn




ā€œA lifecycle event is a regular event with the additional
  feature of providing a mechanism to register direct
 callbacks inside the corresponding document classes
  that are executed when the lifecycle event occurs.ā€


http://www.doctrine-project.org/projects/mongodb_odm/1.0/docs/reference/events/en#lifecycle-callbacks




                                      www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn



ā€¢   preRemove - The preRemove event occurs for a given document before the
    respective DocumentManager remove operation for that document is
    executed.
ā€¢   postRemove - The postRemove event occurs for an document after the
    document has been removed. It will be invoked after the database delete
    operations.
ā€¢   prePersist - The prePersist event occurs for a given document before the
    respective DocumentManager persist operation for that document is executed.
ā€¢   postPersist - The postPersist event occurs for an document after the
    document has been made persistent. It will be invoked after the database insert
    operations. Generated primary key values are available in the postPersist event.
ā€¢   preUpdate - The preUpdate event occurs before the database update
    operations to document data.
ā€¢   postUpdate - The postUpdate event occurs after the database update
    operations to document data.
ā€¢   postLoad - The postLoad event occurs for an document after the document
    has been loaded into the current DocumentManager from the database or after
    the refresh operation has been applied to it.

                                           www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                          Event Examples



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                 #sfdaycgn




                                /**
                                  * @Document
                                  * @HasLifecycleCallbacks
                                  */
                                class BlogPost
                                {
                                     /** @Id */
                                     public $id;
                                     /** @Date */
                                     public $createdAt;
                                     /** @Date */
                                     public $updatedAt;

                                      /** @PreUpdate */
                                      public function prePersist()
                                      {
                                          $this->createdAt = new DateTime();
                                      }

                                      /** @PreUpdate */
                                      public function preUpdate()
                                      {
                                          $this->updatedAt = new DateTime();
                                      }
                                }




                                     www.doctrine-project.org       www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                            Migrating Data



                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                       Initial Document
                                   /**
                                     * @Document
                                     */
                                   class User
                                   {
                                        /** @Id */
                                        public $id;
                                        /** @String */
                                        public $name;
                                   }




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                        New Document
                                 /**
                                   * @Document
                                   */
                                 class User
                                 {
                                      /** @Id */
                                      public $id;
                                      /** @String */
                                      public $firstName;
                                      /** @String */
                                      public $lastName;
                                 }




                                     www.doctrine-project.org   www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                                     #sfdaycgn




         Migrate Documents
         With Old Field Name
                                 /**
                                   * @Document
                                   * @HasLifecycleCallbacks
                                   */
                                 class User
                                 {
                                      /** @Id */
                                      public $id;
                                      /** @String */
                                      public $firstName;
                                      /** @String */
                                      public $lastName;

                                      /** @PreLoad */
                                      public function preLoad(array &$data)
                                      {
                                          if (isset($data['name']))
                                          {
                                              $e = explode(' ', $data['name']);
                                              unset($data['name']);
                                              $data['firstName'] = $e[0];
                                              $data['lastName'] = $e[1];
                                          }
                                      }




                                     www.doctrine-project.org           www.sensiolabs.org
Doctrine MongoDB Object Document Manager                                             #sfdaycgn




                                      Questions?
                                 Jonathan H. Wage
                    ā€¢     http://www.twitter.com/jwage

                    ā€¢     http://www.jwage.com

                    ā€¢     http://www.facebook.com/jwage

              You can contact Jonathan about Doctrine and Open-Source or for
              training, consulting, application development, or business related
                           questions at jonathan.wage@sensio.com



                                     www.doctrine-project.org   www.sensiolabs.org

More Related Content

What's hot

Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
Benjamin Eberlei
Ā 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
Benjamin Eberlei
Ā 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
Scott Hernandez
Ā 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Wez Furlong
Ā 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
G Woo
Ā 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
MongoDB
Ā 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Rifat Nabi
Ā 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
James Williams
Ā 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
HAO-WEN ZHANG
Ā 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Fabien Potencier
Ā 
J query1
J query1J query1
J query1
Manav Prasad
Ā 
J query
J queryJ query
J query
Manav Prasad
Ā 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
Ā 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Hugo Hamon
Ā 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring DataAnton Sulzhenko
Ā 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Hugo Hamon
Ā 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Pavel Makhrinsky
Ā 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
Hugo Hamon
Ā 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionFabien Potencier
Ā 

What's hot (19)

Doctrine and NoSQL
Doctrine and NoSQLDoctrine and NoSQL
Doctrine and NoSQL
Ā 
Doctrine for NoSQL
Doctrine for NoSQLDoctrine for NoSQL
Doctrine for NoSQL
Ā 
MongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with MorphiaMongoDB: Easy Java Persistence with Morphia
MongoDB: Easy Java Persistence with Morphia
Ā 
PHP Data Objects
PHP Data ObjectsPHP Data Objects
PHP Data Objects
Ā 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
Ā 
Simplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with MorphiaSimplifying Persistence for Java and MongoDB with Morphia
Simplifying Persistence for Java and MongoDB with Morphia
Ā 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Ā 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
Ā 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
Ā 
Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3Dependency Injection with PHP and PHP 5.3
Dependency Injection with PHP and PHP 5.3
Ā 
J query1
J query1J query1
J query1
Ā 
J query
J queryJ query
J query
Ā 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
Ā 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
Ā 
MongoDB + Java + Spring Data
MongoDB + Java + Spring DataMongoDB + Java + Spring Data
MongoDB + Java + Spring Data
Ā 
Design Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et PimpleDesign Patterns avec PHP 5.3, Symfony et Pimple
Design Patterns avec PHP 5.3, Symfony et Pimple
Ā 
Drupal Field API. Practical usage
Drupal Field API. Practical usageDrupal Field API. Practical usage
Drupal Field API. Practical usage
Ā 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
Ā 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
Ā 

Similar to Symfony Day 2010 Doctrine MongoDB ODM

Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
Tobias Trelle
Ā 
Webinar: Building Your First MongoDB App
Webinar: Building Your First MongoDB AppWebinar: Building Your First MongoDB App
Webinar: Building Your First MongoDB App
MongoDB
Ā 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
Norberto Leite
Ā 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
sullis
Ā 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
Tobias Trelle
Ā 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
TO THE NEW | Technology
Ā 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
Henrik Ingo
Ā 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDBMongoDB
Ā 
Mongo learning series
Mongo learning series Mongo learning series
Mongo learning series
Prashanth Panduranga
Ā 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10minCorneil du Plessis
Ā 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Railsrfischer20
Ā 
Rails with mongodb
Rails with mongodbRails with mongodb
Rails with mongodb
Kosuke Matsuda
Ā 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHP
ichikaway
Ā 
BedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDB
BedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDBBedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDB
BedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDBTobias Trelle
Ā 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
Will Button
Ā 
Mongodb Training Tutorial in Bangalore
Mongodb Training Tutorial in BangaloreMongodb Training Tutorial in Bangalore
Mongodb Training Tutorial in Bangalore
rajkamaltibacademy
Ā 
MongoDB
MongoDBMongoDB
MongoDB
Steven Francia
Ā 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
Ā 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
MongoDB
Ā 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
Uwe Printz
Ā 

Similar to Symfony Day 2010 Doctrine MongoDB ODM (20)

Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
Ā 
Webinar: Building Your First MongoDB App
Webinar: Building Your First MongoDB AppWebinar: Building Your First MongoDB App
Webinar: Building Your First MongoDB App
Ā 
Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
Ā 
Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012Getting started with MongoDB and Scala - Open Source Bridge 2012
Getting started with MongoDB and Scala - Open Source Bridge 2012
Ā 
Morphia, Spring Data & Co.
Morphia, Spring Data & Co.Morphia, Spring Data & Co.
Morphia, Spring Data & Co.
Ā 
MongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behlMongoDB using Grails plugin by puneet behl
MongoDB using Grails plugin by puneet behl
Ā 
Building Your First MongoDB App
Building Your First MongoDB AppBuilding Your First MongoDB App
Building Your First MongoDB App
Ā 
Building Your First Application with MongoDB
Building Your First Application with MongoDBBuilding Your First Application with MongoDB
Building Your First Application with MongoDB
Ā 
Mongo learning series
Mongo learning series Mongo learning series
Mongo learning series
Ā 
Dependency Injection in Spring in 10min
Dependency Injection in Spring in 10minDependency Injection in Spring in 10min
Dependency Injection in Spring in 10min
Ā 
MongoDB and Ruby on Rails
MongoDB and Ruby on RailsMongoDB and Ruby on Rails
MongoDB and Ruby on Rails
Ā 
Rails with mongodb
Rails with mongodbRails with mongodb
Rails with mongodb
Ā 
How to use MongoDB with CakePHP
How to use MongoDB with CakePHPHow to use MongoDB with CakePHP
How to use MongoDB with CakePHP
Ā 
BedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDB
BedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDBBedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDB
BedCon 2013 - Java Persistenz-Frameworks fĆ¼r MongoDB
Ā 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
Ā 
Mongodb Training Tutorial in Bangalore
Mongodb Training Tutorial in BangaloreMongodb Training Tutorial in Bangalore
Mongodb Training Tutorial in Bangalore
Ā 
MongoDB
MongoDBMongoDB
MongoDB
Ā 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
Ā 
Dev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDBDev Jumpstart: Build Your First App with MongoDB
Dev Jumpstart: Build Your First App with MongoDB
Ā 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
Ā 

More from Jonathan Wage

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Jonathan Wage
Ā 
OpenSky Infrastructure
OpenSky InfrastructureOpenSky Infrastructure
OpenSky InfrastructureJonathan Wage
Ā 
Doctrine In The Real World sflive2011 Paris
Doctrine In The Real World sflive2011 ParisDoctrine In The Real World sflive2011 Paris
Doctrine In The Real World sflive2011 ParisJonathan Wage
Ā 
Doctrine in the Real World
Doctrine in the Real WorldDoctrine in the Real World
Doctrine in the Real World
Jonathan Wage
Ā 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectJonathan Wage
Ā 
Libertyvasion2010
Libertyvasion2010Libertyvasion2010
Libertyvasion2010Jonathan Wage
Ā 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationJonathan Wage
Ā 
Doctrine 2 - Enterprise Persistence Layer For PHP
Doctrine 2 - Enterprise Persistence Layer For PHPDoctrine 2 - Enterprise Persistence Layer For PHP
Doctrine 2 - Enterprise Persistence Layer For PHP
Jonathan Wage
Ā 
Introduction To Doctrine 2
Introduction To Doctrine 2Introduction To Doctrine 2
Introduction To Doctrine 2
Jonathan Wage
Ā 
Doctrine 2 - Not The Same Old Php Orm
Doctrine 2 - Not The Same Old Php OrmDoctrine 2 - Not The Same Old Php Orm
Doctrine 2 - Not The Same Old Php Orm
Jonathan Wage
Ā 
Doctrine 2: Enterprise Persistence Layer for PHP
Doctrine 2: Enterprise Persistence Layer for PHPDoctrine 2: Enterprise Persistence Layer for PHP
Doctrine 2: Enterprise Persistence Layer for PHP
Jonathan Wage
Ā 
Sympal A Cmf Based On Symfony
Sympal   A Cmf Based On SymfonySympal   A Cmf Based On Symfony
Sympal A Cmf Based On SymfonyJonathan Wage
Ā 
Symfony 1.3 + Doctrine 1.2
Symfony 1.3 + Doctrine 1.2Symfony 1.3 + Doctrine 1.2
Symfony 1.3 + Doctrine 1.2
Jonathan Wage
Ā 
Sympal - The flexible Symfony CMS
Sympal - The flexible Symfony CMSSympal - The flexible Symfony CMS
Sympal - The flexible Symfony CMS
Jonathan Wage
Ā 
What's new in Doctrine
What's new in DoctrineWhat's new in Doctrine
What's new in Doctrine
Jonathan Wage
Ā 
What Is Doctrine?
What Is Doctrine?What Is Doctrine?
What Is Doctrine?
Jonathan Wage
Ā 
Sympal - Symfony CMS Preview
Sympal - Symfony CMS PreviewSympal - Symfony CMS Preview
Sympal - Symfony CMS Preview
Jonathan Wage
Ā 
Doctrine Php Object Relational Mapper
Doctrine Php Object Relational MapperDoctrine Php Object Relational Mapper
Doctrine Php Object Relational Mapper
Jonathan Wage
Ā 
Sympal - The Flexible Symfony Cms
Sympal - The Flexible Symfony CmsSympal - The Flexible Symfony Cms
Sympal - The Flexible Symfony Cms
Jonathan Wage
Ā 
What's New In Doctrine
What's New In DoctrineWhat's New In Doctrine
What's New In Doctrine
Jonathan Wage
Ā 

More from Jonathan Wage (20)

Doctrine For Beginners
Doctrine For BeginnersDoctrine For Beginners
Doctrine For Beginners
Ā 
OpenSky Infrastructure
OpenSky InfrastructureOpenSky Infrastructure
OpenSky Infrastructure
Ā 
Doctrine In The Real World sflive2011 Paris
Doctrine In The Real World sflive2011 ParisDoctrine In The Real World sflive2011 Paris
Doctrine In The Real World sflive2011 Paris
Ā 
Doctrine in the Real World
Doctrine in the Real WorldDoctrine in the Real World
Doctrine in the Real World
Ā 
ZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine ProjectZendCon2010 The Doctrine Project
ZendCon2010 The Doctrine Project
Ā 
Libertyvasion2010
Libertyvasion2010Libertyvasion2010
Libertyvasion2010
Ā 
Symfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 IntegrationSymfony2 and Doctrine2 Integration
Symfony2 and Doctrine2 Integration
Ā 
Doctrine 2 - Enterprise Persistence Layer For PHP
Doctrine 2 - Enterprise Persistence Layer For PHPDoctrine 2 - Enterprise Persistence Layer For PHP
Doctrine 2 - Enterprise Persistence Layer For PHP
Ā 
Introduction To Doctrine 2
Introduction To Doctrine 2Introduction To Doctrine 2
Introduction To Doctrine 2
Ā 
Doctrine 2 - Not The Same Old Php Orm
Doctrine 2 - Not The Same Old Php OrmDoctrine 2 - Not The Same Old Php Orm
Doctrine 2 - Not The Same Old Php Orm
Ā 
Doctrine 2: Enterprise Persistence Layer for PHP
Doctrine 2: Enterprise Persistence Layer for PHPDoctrine 2: Enterprise Persistence Layer for PHP
Doctrine 2: Enterprise Persistence Layer for PHP
Ā 
Sympal A Cmf Based On Symfony
Sympal   A Cmf Based On SymfonySympal   A Cmf Based On Symfony
Sympal A Cmf Based On Symfony
Ā 
Symfony 1.3 + Doctrine 1.2
Symfony 1.3 + Doctrine 1.2Symfony 1.3 + Doctrine 1.2
Symfony 1.3 + Doctrine 1.2
Ā 
Sympal - The flexible Symfony CMS
Sympal - The flexible Symfony CMSSympal - The flexible Symfony CMS
Sympal - The flexible Symfony CMS
Ā 
What's new in Doctrine
What's new in DoctrineWhat's new in Doctrine
What's new in Doctrine
Ā 
What Is Doctrine?
What Is Doctrine?What Is Doctrine?
What Is Doctrine?
Ā 
Sympal - Symfony CMS Preview
Sympal - Symfony CMS PreviewSympal - Symfony CMS Preview
Sympal - Symfony CMS Preview
Ā 
Doctrine Php Object Relational Mapper
Doctrine Php Object Relational MapperDoctrine Php Object Relational Mapper
Doctrine Php Object Relational Mapper
Ā 
Sympal - The Flexible Symfony Cms
Sympal - The Flexible Symfony CmsSympal - The Flexible Symfony Cms
Sympal - The Flexible Symfony Cms
Ā 
What's New In Doctrine
What's New In DoctrineWhat's New In Doctrine
What's New In Doctrine
Ā 

Recently uploaded

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
Ā 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
Ā 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
Ā 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
Ā 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
Ā 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
Ā 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
Ā 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
mikeeftimakis1
Ā 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
Ā 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
Ā 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
Ā 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
Ā 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-UniversitƤt
Ā 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Adtran
Ā 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
Ā 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
Ā 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
Ā 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
Ā 
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
UiPathCommunity
Ā 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
Ā 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
Ā 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
Ā 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ā 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Ā 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Ā 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
Ā 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Ā 
Introduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - CybersecurityIntroduction to CHERI technology - Cybersecurity
Introduction to CHERI technology - Cybersecurity
Ā 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Ā 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Ā 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
Ā 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Ā 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Ā 
Pushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 daysPushing the limits of ePRTC: 100ns holdover for 100 days
Pushing the limits of ePRTC: 100ns holdover for 100 days
Ā 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Ā 
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
Ā 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
Ā 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ā 
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder ā€“ active learning and UiPath LLMs for do...
Ā 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
Ā 

Symfony Day 2010 Doctrine MongoDB ODM

  • 1. Doctrine MongoDB Object Document Manager #sfdaycgn Doctrine MongoDB Object Document Mapper (ODM) www.doctrine-project.org www.sensiolabs.org
  • 2. Doctrine MongoDB Object Document Manager #sfdaycgn What is Doctrine? www.doctrine-project.org www.sensiolabs.org
  • 3. Doctrine MongoDB Object Document Manager #sfdaycgn What is Doctrine? ā€¢ Open source PHP project started in 2006 ā€¢ Relational database abstraction layer. ā€¢ mysql, oracle, pgsql, sqlite, etc. ā€¢ Object persistence layers for RDBMS, MongoDB, etc. ā€¢ Other database related functionalities. http://www.doctrine-project.org www.doctrine-project.org www.sensiolabs.org
  • 4. Doctrine MongoDB Object Document Manager #sfdaycgn What is MongoDB? ā€¢ Key-Value document based storage system. ā€¢ Bridge between traditional relational databases and key-value data stores. http://www.mongodb.org www.doctrine-project.org www.sensiolabs.org
  • 5. Doctrine MongoDB Object Document Manager #sfdaycgn Terminology RDBMS MongoDB Database Database Table Collection Row Document www.doctrine-project.org www.sensiolabs.org
  • 6. Doctrine MongoDB Object Document Manager #sfdaycgn Using MongoDB in PHP www.doctrine-project.org www.sensiolabs.org
  • 7. Doctrine MongoDB Object Document Manager #sfdaycgn Connecting $mongo = new Mongo('mongodb://localhost'); www.doctrine-project.org www.sensiolabs.org
  • 8. Doctrine MongoDB Object Document Manager #sfdaycgn Selecting Databases $mongo = new Mongo('mongodb://localhost'); $db = $mongo->selectDB('dbname'); www.doctrine-project.org www.sensiolabs.org
  • 9. Doctrine MongoDB Object Document Manager #sfdaycgn Selecting Collections $mongo = new Mongo('mongodb://localhost'); $db = $mongo->selectDB('dbname'); $coll = $db->selectCollection('users'); www.doctrine-project.org www.sensiolabs.org
  • 10. Doctrine MongoDB Object Document Manager #sfdaycgn Inserting Documents Insert a new user document and echo the newly generated id $user = array( 'username' => 'jwage', 'password' => md5('changeme') 'active' => true ); $coll->insert($user); echo $user['_id']; www.doctrine-project.org www.sensiolabs.org
  • 11. Doctrine MongoDB Object Document Manager #sfdaycgn Updating Documents Update username and password and save the whole document $user = $coll->findOne(array('username' => 'jwage')); $user['username'] = 'jonwage'; $user['password'] = md5('newpassword'); $coll->save($user); www.doctrine-project.org www.sensiolabs.org
  • 12. Doctrine MongoDB Object Document Manager #sfdaycgn Atomic Updates ā€¢ Faster than saving the entire document. ā€¢ Safer than updating the entire document. ā€¢ Updates are done in place and are atomic. www.doctrine-project.org www.sensiolabs.org
  • 13. Doctrine MongoDB Object Document Manager #sfdaycgn Atomic Updates Update username and password where username is jwage $coll->update(array( 'username' => 'jwage' ), array( '$set' => array( 'username' => 'jonwage', 'password' => md5('newpassword') ) )); www.doctrine-project.org www.sensiolabs.org
  • 14. Doctrine MongoDB Object Document Manager #sfdaycgn Atomic Updates Many other atomic operators exist for manipulating a documents data ā€¢ $inc - increments ļ¬eld by the number value ā€¢ $set - sets ļ¬eld to value ā€¢ $unset - deletes a given ļ¬eld ā€¢ $push - appends value to an array ā€¢ $pushAll - appends multiple values to an array ā€¢ $addToSet - appends multiple values to an array that donā€™t already exist in the array ā€¢ $pop - removes the last element in an array ā€¢ $pull - removes all occurrences of a value from an array ā€¢ $pullAll - removes all occurrences of multiple values from an array www.doctrine-project.org www.sensiolabs.org
  • 15. Doctrine MongoDB Object Document Manager #sfdaycgn Removing Documents $coll->remove(array('username' => 'jwage')); www.doctrine-project.org www.sensiolabs.org
  • 16. Doctrine MongoDB Object Document Manager #sfdaycgn Doctrine + MongoDB www.doctrine-project.org www.sensiolabs.org
  • 17. Doctrine MongoDB Object Document Manager #sfdaycgn DocumentManager ā€¢ Abstraction on top of the PHP Mongo class ā€¢ Manages the persistent state of PHP objects ā€¢ Implements UnitOfWork for change tracking http://martinfowler.com/eaaCatalog/unitOfWork.html www.doctrine-project.org www.sensiolabs.org
  • 18. Doctrine MongoDB Object Document Manager #sfdaycgn Document States ā€¢ A NEW document instance has no persistent identity, and is not yet associated with a DocumentManager (i.e. those just created with the "new" operator). ā€¢ A MANAGED document instance is an instance with a persistent identity that is associated with an DocumentManager and whose persistence is thus managed. ā€¢ A DETACHED document instance is an instance with a persistent identity that is not (or no longer) associated with an DocumentManager. ā€¢ A REMOVED document instance is an instance with a persistent identity, associated with an DocumentManager, that will be removed from the database upon transaction commit. www.doctrine-project.org www.sensiolabs.org
  • 19. Doctrine MongoDB Object Document Manager #sfdaycgn DocumentManager Create your DocumentManager instance for managing object persistence $config = new DoctrineODMMongoDBConfiguration(); $config->setMetadataCacheImpl(new DoctrineCommonCacheArrayCache); $driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__."/Documents")); $config->setMetadataDriverImpl($driverImpl); $config->setProxyDir(__DIR__ . '/Proxies'); $config->setProxyNamespace('Proxies'); $dm = DoctrineORMDocumentManager::create($mongo, $config); Wraps around existing $mongo connection www.doctrine-project.org www.sensiolabs.org
  • 20. Doctrine MongoDB Object Document Manager #sfdaycgn Deļ¬ning Document A document is just a regular oleā€™ PHP class class User { private $id; private $username; private $password; public function getId() { return $this->id; } public function getUsername() { return $this->username; } public function setUsername($username) { $this->username = $username; } public function getPassword() { return $this->password; } public function setPassword($password) { $this->password = md5($password); } } www.doctrine-project.org www.sensiolabs.org
  • 21. Doctrine MongoDB Object Document Manager #sfdaycgn Mapping the Document /** @Document */ class User { /** @Id */ private $id; /** @String */ private $username; /** @String */ private $password; // ... } www.doctrine-project.org www.sensiolabs.org
  • 22. Doctrine MongoDB Object Document Manager #sfdaycgn Ready to Go Doctrine now knows about this document and is able to manage its persistent state www.doctrine-project.org www.sensiolabs.org
  • 23. Doctrine MongoDB Object Document Manager #sfdaycgn Inserting, Updating and Deleting Documents www.doctrine-project.org www.sensiolabs.org
  • 24. Doctrine MongoDB Object Document Manager #sfdaycgn Inserting Documents $user = new User(); $user->setUsername('jwage'); $user->setPassword('changeme'); $dm->persist($user); $dm->flush(); // inserts document $users = array( array( 'username' => 'jwage', 'password' => 'changeme' ) ); $coll->batchInsert($users); www.doctrine-project.org www.sensiolabs.org
  • 25. Doctrine MongoDB Object Document Manager #sfdaycgn Updating Documents $user = $dm->findOne('User', array('username' => 'jwage')); $user->setUsername('jonwage'); $user->setPassword('newpassword'); $dm->flush(); // updates document $coll->update( array('_id' => 'theid'), array('$set' => array( 'username' => 'jonwage', 'password' => '5e9d11a14ad1c8dd77e98ef9b53fd1ba' ) ); www.doctrine-project.org www.sensiolabs.org
  • 26. Doctrine MongoDB Object Document Manager #sfdaycgn Removing Documents $user = $dm->findOne('User', array('username' => 'jwage')); $dm->remove($user); $dm->flush(); // removes document $coll->remove(array('_id' => 'theid')); www.doctrine-project.org www.sensiolabs.org
  • 27. Doctrine MongoDB Object Document Manager #sfdaycgn Query API Fluent OO Query API www.doctrine-project.org www.sensiolabs.org
  • 28. Doctrine MongoDB Object Document Manager #sfdaycgn Querying MongoDB Directly // Get user array directly from mongo $user = $mongo->db->users->findOne(array('username' => 'jwage')); Returns an array of information and not a User object www.doctrine-project.org www.sensiolabs.org
  • 29. Doctrine MongoDB Object Document Manager #sfdaycgn Querying Through Doctrine // Get user class instance through Doctrine $user = $dm->findOne('User', array('username' => 'jwage')); Going through Doctrine gives you managed objects back instead of arrays www.doctrine-project.org www.sensiolabs.org
  • 30. Doctrine MongoDB Object Document Manager #sfdaycgn Querying Through Doctrine Query API // Get user class instance through Doctrine Query API $user = $dm->createQuery('User') ->field('username')->equals('jwage') ->getSingleResult(); Query for same user using the Query API www.doctrine-project.org www.sensiolabs.org
  • 31. Doctrine MongoDB Object Document Manager #sfdaycgn Querying Through Doctrine Query API // Find posts within a range of dates $posts = $dm->createQuery('Post') ->field('createdAt')->range($startDate, $endDate) ->execute(); www.doctrine-project.org www.sensiolabs.org
  • 32. Doctrine MongoDB Object Document Manager #sfdaycgn Updating Documents // Update a document $dm->createQuery('User') ->update() ->field('username')->set('jonwage') ->field('password')->set('newpassword') ->field('username')->equals('jwage') ->execute(); www.doctrine-project.org www.sensiolabs.org
  • 33. Doctrine MongoDB Object Document Manager #sfdaycgn Removing Documents // Remove a document $dm->createQuery('User') // Remove a document $dm->createQuery('User') ->remove() ->remove() ->field('username')->equals('jwage') ->execute(); ->field('username')->equals('jwage') ->execute(); www.doctrine-project.org www.sensiolabs.org
  • 34. Doctrine MongoDB Object Document Manager #sfdaycgn Embedded Documents www.doctrine-project.org www.sensiolabs.org
  • 35. Doctrine MongoDB Object Document Manager #sfdaycgn class User { /** @Id */ public $id; /** @String */ public $name; /** @EmbedMany(targetDocument="Address") */ public $addresses = array(); } www.doctrine-project.org www.sensiolabs.org
  • 36. Doctrine MongoDB Object Document Manager #sfdaycgn /** @EmbeddedDocument */ class Address { /** @String */ public $address; /** @String */ public $city; /** @String */ public $state; /** @String */ public $zipcode; } www.doctrine-project.org www.sensiolabs.org
  • 37. Doctrine MongoDB Object Document Manager #sfdaycgn $user = new User(); $user->name = 'Jonathan H. Wage'; $address = new Address(); $address->address = '6512 Mercomatic Ct'; $address->city = 'Nashville'; $address->state = 'Tennessee'; $address->zipcode = '37209'; $user->addresses[] = $address; $dm->persist($user); $dm->flush(); www.doctrine-project.org www.sensiolabs.org
  • 38. Doctrine MongoDB Object Document Manager #sfdaycgn $users = array( array( 'name' => 'Jonathan H. Wage', 'addresses' => array( array( 'address' => '6512 Mercomatic Ct', 'city' => 'Nashville', 'state' => 'Tennesseee', 'zipcode' => '37209' ) ) ) ); $coll->batchInsert($users); www.doctrine-project.org www.sensiolabs.org
  • 39. Doctrine MongoDB Object Document Manager #sfdaycgn Updating Embedded Documents Uses dot notation and atomic operators for updating www.doctrine-project.org www.sensiolabs.org
  • 40. Doctrine MongoDB Object Document Manager #sfdaycgn $user = $dm->findOne('User', array('name' => 'Jonathan H. Wage')); $user->addresses[0]->zipcode = '37205'; $dm->flush(); $coll->update( array('_id' => 'theuserid'), array('$set' => array('addresses.0.zipcode' => '37209')) ); www.doctrine-project.org www.sensiolabs.org
  • 41. Doctrine MongoDB Object Document Manager #sfdaycgn Add New Address www.doctrine-project.org www.sensiolabs.org
  • 42. Doctrine MongoDB Object Document Manager #sfdaycgn $user = $dm->findOne('User', array('name' => 'Jonathan H. Wage')); $address = new Address(); $address->address = '475 Buckhead Ave.'; $address->city = 'Atlanta'; $address->state = 'Georgia'; $address->zipcode = '30305'; $user->addresses[] = $address; $dm->flush(); $coll->update( array('_id' => 'theuserid'), array('$pushAll' => array( 'addresses' => array( array( 'address' => '475 Buckhead Ave.', 'city' => 'Atlanta', 'state' => 'Georgia', 'zipcode' => '30305' ) ) )) ); www.doctrine-project.org www.sensiolabs.org
  • 43. Doctrine MongoDB Object Document Manager #sfdaycgn unset($user->addresses[0]->zipcode); $dm->flush(); $coll->update( array('_id' => 'theuserid'), array( '$unset' => array( 'addresses.0.zipcode' => 1 ) ) ); www.doctrine-project.org www.sensiolabs.org
  • 44. Doctrine MongoDB Object Document Manager #sfdaycgn References MongoDB does not have joins or foreign keys but you can still store references to other documents and resolve the references in your application code. Doctrine abstracts the handling of referneces for you so working with them is seamless. www.doctrine-project.org www.sensiolabs.org
  • 45. Doctrine MongoDB Object Document Manager #sfdaycgn Organization /** @Document */ class Organization { /** @Id */ private $id; /** @String */ private $name; /** @ReferenceMany(targetDocument="User") */ private $users = array(); public function setName($name) { $this->name = $name; } public function addUser(User $user) { $this->users[] = $user; } } www.doctrine-project.org www.sensiolabs.org
  • 46. Doctrine MongoDB Object Document Manager #sfdaycgn User /** @Document */ class User { /** @Id */ private $id; /** @String */ private $name; /** @ReferenceOne(targetDocument="Organization") */ private $organization; public function setName($name) { $this->name = $name; } public function setOrganization(Organization $organization) { $this->organization = $organization; $organization->addUser($this); } } www.doctrine-project.org www.sensiolabs.org
  • 47. Doctrine MongoDB Object Document Manager #sfdaycgn $organization = new Organization(); $organization->setName('Sensio Labs'); $user = new User(); $user->setName('Jonathan H. Wage'); $user->setOrganization($organization); $dm->persist($organization); $dm->persist($user); $dm->flush(); www.doctrine-project.org www.sensiolabs.org
  • 48. Doctrine MongoDB Object Document Manager #sfdaycgn The Result www.doctrine-project.org www.sensiolabs.org
  • 49. Doctrine MongoDB Object Document Manager #sfdaycgn Array ( [_id] => 4c86acd78ead0e8759000000 [name] => Sensio Labs [users] => Array ( [0] => Array ( [$ref] => User [$id] => 4c86acd78ead0e8759010000 [$db] => doctrine_odm_sandbox ) ) ) Array ( [_id] => 4c86acd78ead0e8759010000 [name] => Jonathan H. Wage [organization] => Array ( [$ref] => Organization [$id] => 4c86acd78ead0e8759000000 [$db] => doctrine_odm_sandbox ) ) www.doctrine-project.org www.sensiolabs.org
  • 50. Doctrine MongoDB Object Document Manager #sfdaycgn Working with References www.doctrine-project.org www.sensiolabs.org
  • 51. Doctrine MongoDB Object Document Manager #sfdaycgn $user = $dm->find('User', array('name' => 'Jonathan H. Wage')); // instance of uninitialized OrganizationProxy $organization = $user->getOrganization(); // calling getter or setter for uninitialized proxy // queries the database and initialized the proxy document // query invoked, organization data loaded and doc initialized echo $organization->getName(); www.doctrine-project.org www.sensiolabs.org
  • 52. Doctrine MongoDB Object Document Manager #sfdaycgn $organization = $dm->find('Organization', array('name' => 'Sensio Labs')); $users = $organization->getUsers(); // uninitialized collection // Queries database for users and initializes collection foreach ($users as $user) { // ... } www.doctrine-project.org www.sensiolabs.org
  • 53. Doctrine MongoDB Object Document Manager #sfdaycgn Change Tracking www.doctrine-project.org www.sensiolabs.org
  • 54. Doctrine MongoDB Object Document Manager #sfdaycgn UnitOfWork ā€¢ Tracks changes in objects between ļ¬‚ushes ā€¢ Maintains copy of old values to compare new values to ā€¢ Changesets computed and persisted in the most efļ¬cient way using atomic operators $inc, $set, $unset, $pullAll, $pushAll, etc. www.doctrine-project.org www.sensiolabs.org
  • 55. Doctrine MongoDB Object Document Manager #sfdaycgn Other Features www.doctrine-project.org www.sensiolabs.org
  • 56. Doctrine MongoDB Object Document Manager #sfdaycgn Document Query Language Language for querying documents in a similar way to SQL www.doctrine-project.org www.sensiolabs.org
  • 57. Doctrine MongoDB Object Document Manager #sfdaycgn BNF Grammar www.doctrine-project.org www.sensiolabs.org
  • 58. Doctrine MongoDB Object Document Manager #sfdaycgn QueryLanguage ::= FindQuery | InsertQuery | UpdateQuery | RemoveQuery FindQuery ::= FindClause [WhereClause] [MapClause] [ReduceClause] [SortClause] [LimitClause] [SkipClause] FindClause ::= "FIND" all | SelectField {"," SelectField} SelectField ::= DocumentFieldName SortClause ::= SortClauseField {"," SortClauseField} SortClauseField ::= DocumentFieldName "ASC | DESC" LimitClause ::= "LIMIT" LimitInteger SkipClause ::= "SKIP" SkipInteger MapClause ::= "MAP" MapFunction ReduceClause ::= "REDUCE" ReduceFunction DocumentFieldName ::= DocumentFieldName | EmbeddedDocument "." {"." DocumentFieldName} WhereClause ::= "WHERE" WhereClausePart {"AND" WhereClausePart} WhereClausePart ::= ["all", "not"] DocumentFieldName WhereClauseExpression Value WhereClauseExpression ::= "=" | "!=" | ">=" | "<=" | ">" | "<" | "in" "notIn" | "all" | "size" | "exists" | "type" Value ::= LiteralValue | JsonObject | JsonArray UpdateQuery ::= UpdateClause [WhereClause] UpdateClause ::= [SetExpression], [UnsetExpression], [IncrementExpression], [PushExpression], [PushAllExpression], [PullExpression], [PullAllExpression], [AddToSetExpression], [AddManyToSetExpression], [PopFirstExpression], [PopLastExpression] SetExpression ::= "SET" DocumentFieldName "=" Value {"," SetExpression} UnsetExpression ::= "UNSET" DocumentFieldName {"," UnsetExpression} IncrementExpression ::= "INC" DocumentFieldName "=" IncrementInteger {"," IncrementExpression} PushExpression ::= "PUSH" DocumentFieldName Value {"," PushExpression} PushAllExpression ::= "PUSHALL" DocumentFieldName Value {"," PushAllExpression} PullExpression ::= "PULL" DocumentFieldName Value {"," PullExpression} PullAllExpression ::= "PULLALL" DocumentFieldName Value {"," PullAllExpression} AddToSetExpression ::= "ADDTOSET" DocumentFieldName Value {"," AddToSetExpression} AddManyToSetExpression ::= "ADDMANYTOSET" DocumentFieldName Value {"," AddManyToSetExpression} PopFirstExpression ::= "POPFIRST" DocumentFieldName {"," PopFirstExpression} PopLastExpression ::= "POPLAST" DocumentFieldName {"," PopLastExpression} InsertQuery ::= InsertClause InsertSetClause {"," InsertSetClause} InsertSetClause ::= DocumentFieldName "=" Value RemoveQuery ::= RemoveClause [WhereClause] www.doctrine-project.org www.sensiolabs.org
  • 59. Doctrine MongoDB Object Document Manager #sfdaycgn Creating Query $users = $dm->query('find all FROM User'); www.doctrine-project.org www.sensiolabs.org
  • 60. Doctrine MongoDB Object Document Manager #sfdaycgn Selecting Fields $users = $dm->query('find username FROM User'); www.doctrine-project.org www.sensiolabs.org
  • 61. Doctrine MongoDB Object Document Manager #sfdaycgn Paging Results $users = $dm->query('find all FROM User limit 30 skip 30'); www.doctrine-project.org www.sensiolabs.org
  • 62. Doctrine MongoDB Object Document Manager #sfdaycgn Selecting Slice of Embedded Documents $post = $dm->query('find title, comments limit 20 skip 10 FROM BlogPost WHERE id = ?', array($id)); www.doctrine-project.org www.sensiolabs.org
  • 63. Doctrine MongoDB Object Document Manager #sfdaycgn Other Examples // Find all posts greater than or equal to a date $posts = $dm->query('find all FROM BlogPost WHERE createdAt >= ?', array($date)); // Find all posts sorted by created at desc $posts = $dm->query('find all FROM BlogPost sort createdAt desc'); // Update user $dm->query('update DocumentsUser set password = ? where username = ?', array('newpassword', 'jwage')); www.doctrine-project.org www.sensiolabs.org
  • 64. Doctrine MongoDB Object Document Manager #sfdaycgn Lifecycle Events www.doctrine-project.org www.sensiolabs.org
  • 65. Doctrine MongoDB Object Document Manager #sfdaycgn ā€œA lifecycle event is a regular event with the additional feature of providing a mechanism to register direct callbacks inside the corresponding document classes that are executed when the lifecycle event occurs.ā€ http://www.doctrine-project.org/projects/mongodb_odm/1.0/docs/reference/events/en#lifecycle-callbacks www.doctrine-project.org www.sensiolabs.org
  • 66. Doctrine MongoDB Object Document Manager #sfdaycgn ā€¢ preRemove - The preRemove event occurs for a given document before the respective DocumentManager remove operation for that document is executed. ā€¢ postRemove - The postRemove event occurs for an document after the document has been removed. It will be invoked after the database delete operations. ā€¢ prePersist - The prePersist event occurs for a given document before the respective DocumentManager persist operation for that document is executed. ā€¢ postPersist - The postPersist event occurs for an document after the document has been made persistent. It will be invoked after the database insert operations. Generated primary key values are available in the postPersist event. ā€¢ preUpdate - The preUpdate event occurs before the database update operations to document data. ā€¢ postUpdate - The postUpdate event occurs after the database update operations to document data. ā€¢ postLoad - The postLoad event occurs for an document after the document has been loaded into the current DocumentManager from the database or after the refresh operation has been applied to it. www.doctrine-project.org www.sensiolabs.org
  • 67. Doctrine MongoDB Object Document Manager #sfdaycgn Event Examples www.doctrine-project.org www.sensiolabs.org
  • 68. Doctrine MongoDB Object Document Manager #sfdaycgn /** * @Document * @HasLifecycleCallbacks */ class BlogPost { /** @Id */ public $id; /** @Date */ public $createdAt; /** @Date */ public $updatedAt; /** @PreUpdate */ public function prePersist() { $this->createdAt = new DateTime(); } /** @PreUpdate */ public function preUpdate() { $this->updatedAt = new DateTime(); } } www.doctrine-project.org www.sensiolabs.org
  • 69. Doctrine MongoDB Object Document Manager #sfdaycgn Migrating Data www.doctrine-project.org www.sensiolabs.org
  • 70. Doctrine MongoDB Object Document Manager #sfdaycgn Initial Document /** * @Document */ class User { /** @Id */ public $id; /** @String */ public $name; } www.doctrine-project.org www.sensiolabs.org
  • 71. Doctrine MongoDB Object Document Manager #sfdaycgn New Document /** * @Document */ class User { /** @Id */ public $id; /** @String */ public $firstName; /** @String */ public $lastName; } www.doctrine-project.org www.sensiolabs.org
  • 72. Doctrine MongoDB Object Document Manager #sfdaycgn Migrate Documents With Old Field Name /** * @Document * @HasLifecycleCallbacks */ class User { /** @Id */ public $id; /** @String */ public $firstName; /** @String */ public $lastName; /** @PreLoad */ public function preLoad(array &$data) { if (isset($data['name'])) { $e = explode(' ', $data['name']); unset($data['name']); $data['firstName'] = $e[0]; $data['lastName'] = $e[1]; } } www.doctrine-project.org www.sensiolabs.org
  • 73. Doctrine MongoDB Object Document Manager #sfdaycgn Questions? Jonathan H. Wage ā€¢ http://www.twitter.com/jwage ā€¢ http://www.jwage.com ā€¢ http://www.facebook.com/jwage You can contact Jonathan about Doctrine and Open-Source or for training, consulting, application development, or business related questions at jonathan.wage@sensio.com www.doctrine-project.org www.sensiolabs.org