Doctrine ORM Good Practices and Tricks

I’d like to share with you a very good video From Marco Pivetta who is part of the Doctrine Project core team

Tried to summarize the video in points:

  1. Doctrine is for: OLTP, DDD, Object Oriented, not for reporting, use SQL instead
  2. Entities should work without ORM and without DB
  3. Design the Entities first
  4. Entities represent your Domain
  5. Design the database after modeling your domain
  6. Entities are not typed array
  7. You have to think about how objects talk to each other instead of what the objects contain
  8. No behavior = No need for ORM
  9. Respect Law of Demeter (LOD) https://en.wikipedia.org/wiki/Law_of_Demeter
  10. Keep collections hidden in your Entities
  11. Entities should always be in a valid state
  12. Use named constructors, ex. public static function fromUserInput()
  13. Avoid entity Setters
  14. Don’t couple with the application layer
  15. Avoid writing business logic inside LifeCycle Callback
  16. Avoid auto-generated identifiers, use UUID instead
  17. Avoid derived primary keys, use UNIQUE instead
  18. Avoid composite primary keys
  19. Don’t deal with UNIQUE constraint problem inside the application
  20. Try to design data structures in such a way that are append only
  21. Avoid soft deletes, as they break data integrity, use audit log or archiving instead
  22. Use Annotations Mapping in private packages
  23. Use XML Mapping in public packages
  24. Eager loading is useless, avoid it
  25. Avoid Bi-Directional Associations, because they are overhead, use DQL instead
  26. Use custom repositories for improved expressiveness
  27. Query functions are better than repositories
  28. Avoid ObjectManager::getRepository(), as it is a ServiceLocator, inject Repositories instead
  29. Use $repository->find() that can return null
  30. Use $repository->get() that throws exceptions to simplify error logic and can not return null
  31. Avoid two-phase commit
  32. Communicate between boundaries via identifiers not object references
  33. The Paginator is a monster, use custom query instead
  34. Do not normalize without the need for it, Otherwise you’re digging your own grave
  35. Consider using Separate DBs (Transactional Data != Reporting Data)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.