SlideShare une entreprise Scribd logo
1  sur  49
Télécharger pour lire hors ligne
Doctrine MongoDB ODM
        Kris Wallsmith




         October 19, 2010
@kriswallsmith

•   Symfony Release Manager

•   Doctrine Team

•   Senior Software Engineer at

•   10 years experience with PHP and web development

•   Open source evangelist and international speaker
This is MongoDB…
$mongo = new Mongo();
$db = $mongo->pdxphp;

$db->people->save(array(
    'name' => 'Kris Wallsmith',
));
$cursor = $db->people->find();
print_r(iterator_to_array($cursor));
Array
(
    [4cbdffdae84ded424f000000] => Array
        (
            [_id] => MongoId Object
            [name] => Kris Wallsmith
        )
)
MongoDB is where you
put your arrays for later.
$db->people->save(array(
    'name' => 'Sam Keen',
    'roles' => array(
        'organizer',
        'presenter',
    ),
));
$query = array('roles' => 'presenter');

$cursor = $db->people->find($query);

print_r(iterator_to_array($cursor));
Array
(
    [4cbe03cfe84dedb850010000] => Array
        (
            [_id] => MongoId Object
            [name] => Sam Keen
            [roles] => Array
                (
                    [0] => organizer
                    [1] => presenter
                )

        )
)
Me too!
$query = array(
    'name' => 'Kris Wallsmith',
);

$kris = $db->people->findOne($query);
$kris['roles'] = array('presenter');

$db->people->save($kris);
$query = array('roles' => 'presenter');
$fields = array('name');

$cursor = $db->people->find($query, $fields);

print_r(iterator_to_array($cursor));
Array
(
    [4cbe0a9de84ded7952010000] => Array
        (
            [_id] => MongoId Object
            [name] => Sam Keen
        )
    [4cbe0a9de84ded7952000000] => Array
        (
            [_id] => MongoId Object
            [name] => Kris Wallsmith
        )
)
Be surgical.
$query = array('roles' => 'presenter');

$update = array(
    '$push' => array(
      'roles' => 'cool guy',
    ),
);

$db->people->update($query, $update);
Atomic Operators

• $inc                • $addToSet
• $set                • $pop
• $unset              • $pull
• $push               • $pullAll
• $pushAll            • $rename
Advanced Queries
$roles = array('organizer', 'presenter');

$db->people->find(array(
    'roles' => array('$all' => $roles),
));
Conditional Operators

• $ne               • $size
• $in               • $exists
• $nin              • $type
• $mod              • $or
• $all              • $elemMatch
Cursor Methods
$cursor = $db->people->find();
$cursor->sort(array('name' => 1));

foreach ($cursor as $person) {
    // ...
}
I like you, Sam.
$samRef = MongoDBRef::create('people', $samId);

$db->people->update(
    array('_id' => $kris['_id']),
    array(
        '$addToSet' => array(
            'likes' => $samRef,
        ),
    )
);
$sam = $db->getDBRef($samRef);
$db->people->find(array(
    'likes.$id' => $kris['_id'],
));
Terminology
 RDBMS           MongoDB

 Database         Database

   Table          Collection

   Row            Document

Foreign Key   Database Reference
A document is an array.
Arrays are nice.
Objects are better.*


                       * Whenever objects are better.
The Doctrine MongoDB
Object Document Mapper
    maps documents
  to and from objects.
We just need to tell it how.
/** @Document(collection="people") */
class Person {
  /** @Id */
  public $id;
  /** @String */
  public $name;
  /** @Collection */
  public $roles = array();
  /** @ReferenceMany */
  public $likes = array();
  /** @EmbedMany(targetDocument="Address") */
  public $addresses = array();
}
POPO FTW!
$kris = new Person();
$kris->name = 'Kris Wallsmith';
$kris->roles[] = 'presenter';
$kris->likes[] = $sam;
$kris->addresses[] = $homeAddy;

$documentManager->persist($kris);
$documentManager->flush();
Wherefore art thou
  ->save()
        ?
Documents




Controller               Document
                          Manager
ActiveRecord is more abstract.
Doctrine calculates the
optimal query for you.
$kris = $dm->findOne('Person', array(
    'name' => 'Kris Wallsmith',
));

$kris->roles[] = 'cool guy';

$dm->flush();
$db->people->update(array(
    '_id' => $kris->id,
), array(
    '$push' => array(
        'roles' => 'cool guy',
    ),
));
Query API
$query = $dm->createQuery('Person')
  ->field('name')->notEqual('Kris Wallsmith')
  ->field('roles')->equals('presenter')
  ->sort('name', 'asc');

$cursor = $query->execute();
Lifecycle Callbacks
/** @Document @HasLifecycleCallbacks */
class Foo
{
  /** @Timestamp */
  public $createdAt;

    /** @PrePersist */
    public function ensureCreatedAt() {
      $this->createdAt = new DateTime();
    }
}
OpenSky is Hiring!
  http://engineering.shopopensky.com

 Please contact me if you're interested.
OpenSky is Hiring!
  http://engineering.shopopensky.com

 Please contact me if you're interested.
mongodb.org

doctrine-project.org

symfony-reloaded.org

Contenu connexe

Tendances

Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
Fabien Potencier
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
Bill Chang
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
Hugo Hamon
 

Tendances (20)

Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
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
 
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo EditionLithium: The Framework for People Who Hate Frameworks, Tokyo Edition
Lithium: The Framework for People Who Hate Frameworks, Tokyo Edition
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010Symfony2 - WebExpo 2010
Symfony2 - WebExpo 2010
 
Nubilus Perl
Nubilus PerlNubilus Perl
Nubilus Perl
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Looping the Loop with SPL Iterators
Looping the Loop with SPL IteratorsLooping the Loop with SPL Iterators
Looping the Loop with SPL Iterators
 
Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3Symfony 2.0 on PHP 5.3
Symfony 2.0 on PHP 5.3
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
Symfony War Stories
Symfony War StoriesSymfony War Stories
Symfony War Stories
 
Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12Symfony components in the wild, PHPNW12
Symfony components in the wild, PHPNW12
 
Speed up your developments with Symfony2
Speed up your developments with Symfony2Speed up your developments with Symfony2
Speed up your developments with Symfony2
 
Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5Rich domain model with symfony 2.5 and doctrine 2.5
Rich domain model with symfony 2.5 and doctrine 2.5
 

Similaire à Doctrine MongoDB ODM (PDXPHP)

DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
chuvainc
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
Taras Kalapun
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Masahiro Nagano
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
waraiotoko
 

Similaire à Doctrine MongoDB ODM (PDXPHP) (20)

Taking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order FunctionsTaking Perl to Eleven with Higher-Order Functions
Taking Perl to Eleven with Higher-Order Functions
 
Redis for the Everyday Developer
Redis for the Everyday DeveloperRedis for the Everyday Developer
Redis for the Everyday Developer
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 
An Elephant of a Different Colour: Hack
An Elephant of a Different Colour: HackAn Elephant of a Different Colour: Hack
An Elephant of a Different Colour: Hack
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
Designing Opeation Oriented Web Applications / YAPC::Asia Tokyo 2011
 
Coding Horrors
Coding HorrorsCoding Horrors
Coding Horrors
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 
Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)
 
DBI
DBIDBI
DBI
 
究極のコントローラを目指す
究極のコントローラを目指す究極のコントローラを目指す
究極のコントローラを目指す
 
Zf Zend Db by aida
Zf Zend Db by aidaZf Zend Db by aida
Zf Zend Db by aida
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Database api
Database apiDatabase api
Database api
 
Php functions
Php functionsPhp functions
Php functions
 
Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)
 
PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)
 

Plus de Kris Wallsmith

Plus de Kris Wallsmith (14)

Matters of State
Matters of StateMatters of State
Matters of State
 
The View From Inside
The View From InsideThe View From Inside
The View From Inside
 
How kris-writes-symfony-apps-london
How kris-writes-symfony-apps-londonHow kris-writes-symfony-apps-london
How kris-writes-symfony-apps-london
 
Drupal, meet Assetic
Drupal, meet AsseticDrupal, meet Assetic
Drupal, meet Assetic
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Love and Loss: A Symfony Security Play
Love and Loss: A Symfony Security PlayLove and Loss: A Symfony Security Play
Love and Loss: A Symfony Security Play
 
How Kris Writes Symfony Apps
How Kris Writes Symfony AppsHow Kris Writes Symfony Apps
How Kris Writes Symfony Apps
 
Assetic (Zendcon)
Assetic (Zendcon)Assetic (Zendcon)
Assetic (Zendcon)
 
Assetic (OSCON)
Assetic (OSCON)Assetic (OSCON)
Assetic (OSCON)
 
Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)Assetic (Symfony Live Paris)
Assetic (Symfony Live Paris)
 
Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3Introducing Assetic: Asset Management for PHP 5.3
Introducing Assetic: Asset Management for PHP 5.3
 
A Practical Introduction to Symfony2
A Practical Introduction to Symfony2A Practical Introduction to Symfony2
A Practical Introduction to Symfony2
 
Symfony 2
Symfony 2Symfony 2
Symfony 2
 
Symfony in the Cloud
Symfony in the CloudSymfony in the Cloud
Symfony in the Cloud
 

Dernier

Dernier (20)

A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

Doctrine MongoDB ODM (PDXPHP)