Overview
Syllabus
Intro
DOCTRINE PROJECT A group of persistence-oriented libraries for PHP
WE ARE LOOKING FOR CONTRIBUTORS! (Must be prepared to take unpopular decisions)
DOCTRINE 2 ORM BEST PRACTICES
KNOW YOUR ENEMY
OLTP
FAST PROTOTYPING
DYNAMIC DATA STRUCTURES
REPORTING That's what SQL is for It's a QUERY language, after all
ENTITIES (OF COURSE) Entities should work without the ORM Entities should work without the DB
ENTITIES (MOSTLY) REPRESENT YOUR DOMAIN
THE DATABASE IS JUST SAVING THINGS
DESIGN ENTITIES FIRST
DEFINE THE DATABASE AFTER MODELING YOUR DOMAIN
DEFINE MAPPINGS AFTER DESIGNING THE ENTITIES
DESIGNING ENTITIES
ENTITIES ARE NOT TYPED ARRAYS
ENTITIES HAVE BEHAVIOR
ENTITY INTERNAL STATE DESIGN IS IRRELEVANT You can deal with state after designing the API Designing State-first leads to terrible coupling
RESPECT THE LOD
DISALLOW COLLECTION ACCESS FROM OUTSIDE THE ENTITY
STAY VALID AFTER _CONSTRUCT (Regardless of the DB) Named constructors are OK
AVOID SETTERS
AVOID COUPLING WITH THE APPLICATION LAYER
FORM COMPONENTS BREAK ENTITY VALIDITY
AVOID LIFECYCLE CALLBACKS
LIFECYCLE CALLBACKS ARE A PERSISTENCE HACK
AUTO INCREMENT IS ABUSED FOR SORTING Are you looking for a DATETIME field instead?
AVOID DERIVED PRIMARY KEYS You are just normalizing for the sake of it Does your domain really NEED it?
AVOID COMPOSITE PRIMARY KEYS Any reason to not use an unique constraint instead? Do they make a difference in your domain?
FAVOUR IMMUTABLE ENTITIES Or append-only data-structures
Immutable data is simple Immutable data is cacheable (forever) Immutable data is predictable Immutable data enables historical analysis
AVOID SOFT-DELETES
SOFT DELETES ARE A BROKEN IDEA
SOFT DELETES BREAK DATA INTEGRITY (and therefore validity)
Soft Deletes can usually be replaced with more specific domain concepts
MAPPING DRIVER CHOICE
USE ANNOTATIONS IN PRIVATE PACKAGES
USE XML MAPPINGS IN PUBLIC PACKAGES
LAZY OR EAGER?
EAGER LOADING IS USELESS
EXTRA LAZY INDICATES HIGH RISK AREAS We reach the limits of the ORM Careful about performance/transaction size!
AVOID BI-DIRECTIONAL ASSOCIATIONS
BI-DIRECTIONAL ASSOCIATIONS ARE OVERHEAD
USE CUSTOM REPOSITORIES FOR IMPROVED EXPRESSIVENESS
REPOSITORIES ARE SERVICES So are Query Functions
INJECT REPOSITORIES INSTEAD
KEEP NORMALIZATION UNDER CONTROL
KEEP NORMALIZATION (FREAKS) UNDER CONTROL
You may need to gag your DBAs... Or get them to understand your needs Academic and practical knowledge may differ
WHAT ABOUT PERFORMANCE?
RECAP
DOMAIN FIRST
DO NOT NORMALIZE WITHOUT A NEED FOR IT Otherwise, you're digging your own grave!
CONSIDER USING SEPARATE DBS Transactional Data
Taught by
PHP UK Conference