SlideShare uma empresa Scribd logo
1 de 23
This Document is Confidential
Doctrine ORM Internals
UnitOfWork
Ilya Antipenko
Software Engineer Trainer at Oro Inc.
iantypenko@oroinc.com
https://github.com/aivus
What is The Doctrine Project?
Annotations
Cache
Coding Standard
Collections
Common
Database Abstraction Layer
Event Manager
Inflector
Instantiator
Lexer
The Doctrine Project is the home to several PHP libraries primarily focused on database storage and object
mapping.
Migrations
MongoDB Abstraction Layer
MongoDB Object Document Mapper
Object Relational Mapper
Persistence
PHPCR ODM
Reflection
RST Parser
Skeleton Mapper
Doctrine ORM
PHP object relational mapper (ORM) that sits on top of a powerful database abstraction layer (DBAL).
https://martinfowler.com/eaaCatalog/dataMapper.html
The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data
between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn't know even that there's a
database present; they need no SQL interface code, and certainly no knowledge of the database schema.
Entity Manager
- persist
- flush
- merge
- detach
- remove
- refresh
- clear
- ...
- persist
- commit
- merge
- detach
- remove
- refresh
- clear
- ...
The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM
subsystems such as UnitOfWork, Query Language and Repository API.
EntityManager UnitOfWork
EntityManager::persist
Tells the EntityManager to make an instance managed and persistent.
persist() methods is not so smart as a lot of developers think.
This method:
1. Checks that doctrine has metadata for this entity
2. If this entity doesn’t have filled id (in most cases) - mark it with state=STATE_NEW
3. Call prePersist event
4. Generate id (if possible)
5. Schedule this entity for inserting
(!) This method doesn’t construct SQL for insert.
EntityManager::flush
Flushes all changes to objects that have been queued up to now to the database. This effectively
synchronizes the in-memory state of managed objects with the database.
This method:
1. Dispatches preFlush event
2. Calculates change set based on scheduled (for insert/delete/etc) entities.
3. Dispatch onFlush
4. Start transaction
5. Execute inserts, updates, extra updates
6. Collection deletes
7. Collection updates (delete/update/insert row)
8. Execute deletions
9. Dispatch postFlush
10. Clear up internal state
EntityManager::close
Closes the EntityManager. All entities that are currently managed by this EntityManager become detached.
The EntityManager may no longer be used after it is closed.
Exception “The EntityManager is closed.” will thrown in case of using EM after closing it.
EM can be closed manually by calling close() method or in case of error during the transaction process in
UnitOfWork::commit()
$em->close();
EntityManager::merge
Merges the state of a detached entity into the persistence context of this EntityManager and returns the
managed copy of the entity. The entity passed to merge will not become associated/managed with this
EntityManager.
You should use result of this call in your code:
$managedEntity = $em->merge($detachedEntity);
EntityManager::detach
Detaches an entity from the persistence management. It's persistence will no longer be managed by Doctrine.
$em->detach($entity);
EntityManager::remove
Removes an entity instance.
A removed entity will be removed from the database at or before transaction commit or as a result of the flush
operation.
$em->remove($entity);
EntityManager::refresh
Refreshes the state of the given entity from the database, overwriting any local, unpersisted changes.
$em->refresh($entity);
EntityManager::clear
Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.
$em->clear();
UnitOfWork
UnitOfWork class implements UnitOfWork pattern.
This class responsible for maintaining a list of objects affected by a business transaction and coordinates the writing out of
changes and the resolution of concurrency problems.
https://martinfowler.com/eaaCatalog/unitOfWork.html
Persisters
Entity Persisters Collection Persisters
UnitOfWork states
STATE_MANAGED - Persisted entity, UoW tracks state of this entity
STATE_NEW - New entity and is not managed by EntityManager yet.
STATE_DETACHED - Persisted entity (with identifier), but EntityManager doesn’t track changes
STATE_REMOVED - Persisted entity but scheduled for removing
UnitOfWork Identity Map
The identity map that holds references to all managed entities that have an identity.
The entities are grouped by their class name.
Since all classes in a hierarchy must share the same identifier set, we always take the root class
name of the hierarchy.
UnitOfWork Original Entity Data
Map of the original entity data of managed entities
Keys are object ids (spl_object_hash).
This is used for calculating changesets at commit time.
Doctrine events
- Doctrine bundle entity events
- Lifecycle event
- preRemove
- postRemove
- prePersist
- postPersist
- preUpdate
- postUpdate
- postLoad
- loadClassMetadata
- onClassMetadataNotFound
- preFlush
- onFlush
- postFlush
- onClear
- Symfony DoctrineBundle event:
- Tag “doctrine.orm.entity_listener” - allows to subscribe on specific entity
Don’t call EntityManager::flush() in listeners
Bonus: extra updates (internal)
UnitOfWork::scheduleExtraUpadate
Schedules an extra update that will be executed immediately after the regular entity updates within
the currently running commit cycle.
Can be used to add additional updates during lifecycle events.
For example in postPersist or postUpdate
$uow->scheduleExtraUpdate($entity, ['entityId' => [null, $id]]);
Demo time
https://github.com/ilya-antipenko/doctrine-uow
Hub Post AuditLogManyToMany
Simple representation of blog
post
Representation of
category (hub) like in
Habrahabr
Log of changes in any
entities in the system
Questions?

Mais conteúdo relacionado

Mais procurados

BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization BlueHat Security Conference
 
Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular applicationSuresh Patidar
 
Spring introduction
Spring introductionSpring introduction
Spring introductionManav Prasad
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by defaultSecuRing
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdfkumari36
 
Vulnerable_and_outdated_components_suman.pptx
Vulnerable_and_outdated_components_suman.pptxVulnerable_and_outdated_components_suman.pptx
Vulnerable_and_outdated_components_suman.pptxSuman Astani
 
Learn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAPLearn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAPPaul Ionescu
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JSCakra Danu Sedayu
 
Android Security & Penetration Testing
Android Security & Penetration TestingAndroid Security & Penetration Testing
Android Security & Penetration TestingSubho Halder
 
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida  Android run time hooking - Bhargav Gajera & Vitthal ShindeFrida  Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida Android run time hooking - Bhargav Gajera & Vitthal ShindeNSConclave
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
02. input validation module v5
02. input validation module v502. input validation module v5
02. input validation module v5Eoin Keary
 

Mais procurados (20)

BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
BlueHat v17 || Dangerous Contents - Securing .Net Deserialization
 
Postman
PostmanPostman
Postman
 
OWASP Top 10 Project
OWASP Top 10 ProjectOWASP Top 10 Project
OWASP Top 10 Project
 
Web worker in your angular application
Web worker in your angular applicationWeb worker in your angular application
Web worker in your angular application
 
Spring introduction
Spring introductionSpring introduction
Spring introduction
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Applications secure by default
Applications secure by defaultApplications secure by default
Applications secure by default
 
Constructors in Java (2).pdf
Constructors in Java (2).pdfConstructors in Java (2).pdf
Constructors in Java (2).pdf
 
Vulnerable_and_outdated_components_suman.pptx
Vulnerable_and_outdated_components_suman.pptxVulnerable_and_outdated_components_suman.pptx
Vulnerable_and_outdated_components_suman.pptx
 
Learn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAPLearn to pen-test with OWASP ZAP
Learn to pen-test with OWASP ZAP
 
Spring security
Spring securitySpring security
Spring security
 
Build RESTful API Using Express JS
Build RESTful API Using Express JSBuild RESTful API Using Express JS
Build RESTful API Using Express JS
 
Android Security & Penetration Testing
Android Security & Penetration TestingAndroid Security & Penetration Testing
Android Security & Penetration Testing
 
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida  Android run time hooking - Bhargav Gajera & Vitthal ShindeFrida  Android run time hooking - Bhargav Gajera & Vitthal Shinde
Frida Android run time hooking - Bhargav Gajera & Vitthal Shinde
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Spring boot
Spring bootSpring boot
Spring boot
 
OAuth 2.0
OAuth 2.0OAuth 2.0
OAuth 2.0
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
02. input validation module v5
02. input validation module v502. input validation module v5
02. input validation module v5
 

Semelhante a Doctrine ORM Internals. UnitOfWork

Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2Haitham Raik
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate IntroductionRanjan Kumar
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 FrameworkEmprovise
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)ejlp12
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture ComponentsDarshan Parikh
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreIMC Institute
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1b_kathir
 

Semelhante a Doctrine ORM Internals. UnitOfWork (20)

TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Drools
DroolsDrools
Drools
 
Advanced Hibernate V2
Advanced Hibernate V2Advanced Hibernate V2
Advanced Hibernate V2
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
02 Hibernate Introduction
02 Hibernate Introduction02 Hibernate Introduction
02 Hibernate Introduction
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 Framework
 
Jpa 2.1 Application Development
Jpa 2.1 Application DevelopmentJpa 2.1 Application Development
Jpa 2.1 Application Development
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
Hello Android
Hello AndroidHello Android
Hello Android
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
04 Data Access
04 Data Access04 Data Access
04 Data Access
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture Components
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Struts2.x
Struts2.xStruts2.x
Struts2.x
 
Hibernate Session 1
Hibernate Session 1Hibernate Session 1
Hibernate Session 1
 

Último

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 

Último (20)

Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 

Doctrine ORM Internals. UnitOfWork

  • 1. This Document is Confidential Doctrine ORM Internals UnitOfWork
  • 2. Ilya Antipenko Software Engineer Trainer at Oro Inc. iantypenko@oroinc.com https://github.com/aivus
  • 3. What is The Doctrine Project? Annotations Cache Coding Standard Collections Common Database Abstraction Layer Event Manager Inflector Instantiator Lexer The Doctrine Project is the home to several PHP libraries primarily focused on database storage and object mapping. Migrations MongoDB Abstraction Layer MongoDB Object Document Mapper Object Relational Mapper Persistence PHPCR ODM Reflection RST Parser Skeleton Mapper
  • 4. Doctrine ORM PHP object relational mapper (ORM) that sits on top of a powerful database abstraction layer (DBAL). https://martinfowler.com/eaaCatalog/dataMapper.html The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn't know even that there's a database present; they need no SQL interface code, and certainly no knowledge of the database schema.
  • 5. Entity Manager - persist - flush - merge - detach - remove - refresh - clear - ... - persist - commit - merge - detach - remove - refresh - clear - ... The EntityManager is the central access point to ORM functionality. It is a facade to all different ORM subsystems such as UnitOfWork, Query Language and Repository API. EntityManager UnitOfWork
  • 6. EntityManager::persist Tells the EntityManager to make an instance managed and persistent. persist() methods is not so smart as a lot of developers think. This method: 1. Checks that doctrine has metadata for this entity 2. If this entity doesn’t have filled id (in most cases) - mark it with state=STATE_NEW 3. Call prePersist event 4. Generate id (if possible) 5. Schedule this entity for inserting (!) This method doesn’t construct SQL for insert.
  • 7. EntityManager::flush Flushes all changes to objects that have been queued up to now to the database. This effectively synchronizes the in-memory state of managed objects with the database. This method: 1. Dispatches preFlush event 2. Calculates change set based on scheduled (for insert/delete/etc) entities. 3. Dispatch onFlush 4. Start transaction 5. Execute inserts, updates, extra updates 6. Collection deletes 7. Collection updates (delete/update/insert row) 8. Execute deletions 9. Dispatch postFlush 10. Clear up internal state
  • 8. EntityManager::close Closes the EntityManager. All entities that are currently managed by this EntityManager become detached. The EntityManager may no longer be used after it is closed. Exception “The EntityManager is closed.” will thrown in case of using EM after closing it. EM can be closed manually by calling close() method or in case of error during the transaction process in UnitOfWork::commit() $em->close();
  • 9. EntityManager::merge Merges the state of a detached entity into the persistence context of this EntityManager and returns the managed copy of the entity. The entity passed to merge will not become associated/managed with this EntityManager. You should use result of this call in your code: $managedEntity = $em->merge($detachedEntity);
  • 10. EntityManager::detach Detaches an entity from the persistence management. It's persistence will no longer be managed by Doctrine. $em->detach($entity);
  • 11. EntityManager::remove Removes an entity instance. A removed entity will be removed from the database at or before transaction commit or as a result of the flush operation. $em->remove($entity);
  • 12. EntityManager::refresh Refreshes the state of the given entity from the database, overwriting any local, unpersisted changes. $em->refresh($entity);
  • 13. EntityManager::clear Clears the EntityManager. All entities that are currently managed by this EntityManager become detached. $em->clear();
  • 14. UnitOfWork UnitOfWork class implements UnitOfWork pattern. This class responsible for maintaining a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems. https://martinfowler.com/eaaCatalog/unitOfWork.html
  • 16. UnitOfWork states STATE_MANAGED - Persisted entity, UoW tracks state of this entity STATE_NEW - New entity and is not managed by EntityManager yet. STATE_DETACHED - Persisted entity (with identifier), but EntityManager doesn’t track changes STATE_REMOVED - Persisted entity but scheduled for removing
  • 17. UnitOfWork Identity Map The identity map that holds references to all managed entities that have an identity. The entities are grouped by their class name. Since all classes in a hierarchy must share the same identifier set, we always take the root class name of the hierarchy.
  • 18. UnitOfWork Original Entity Data Map of the original entity data of managed entities Keys are object ids (spl_object_hash). This is used for calculating changesets at commit time.
  • 19. Doctrine events - Doctrine bundle entity events - Lifecycle event - preRemove - postRemove - prePersist - postPersist - preUpdate - postUpdate - postLoad - loadClassMetadata - onClassMetadataNotFound - preFlush - onFlush - postFlush - onClear - Symfony DoctrineBundle event: - Tag “doctrine.orm.entity_listener” - allows to subscribe on specific entity
  • 21. Bonus: extra updates (internal) UnitOfWork::scheduleExtraUpadate Schedules an extra update that will be executed immediately after the regular entity updates within the currently running commit cycle. Can be used to add additional updates during lifecycle events. For example in postPersist or postUpdate $uow->scheduleExtraUpdate($entity, ['entityId' => [null, $id]]);
  • 22. Demo time https://github.com/ilya-antipenko/doctrine-uow Hub Post AuditLogManyToMany Simple representation of blog post Representation of category (hub) like in Habrahabr Log of changes in any entities in the system