Doctrine Basics
Introducing ORM Concepts and Doctrine framework,
Entities, Repositories
Contents
• ORM Basics - Doctrine
• Entity Manager
• Entity Repository
2
ORM BASICS - DOCTRINE
Doctrine DBAL, Doctrine ORM
What Is ORM?
• ORM - Object Relational Mapper
• Maps PHP objects to database table rows
• Database independent
• Has its own SQL-like language
4
What Is ORM?
Doctrine ORM
• Map database row to PHP object called Entity
Doctrine ORM
• Doctrine entities should live in src/Entity directory
Doctrine ORM
• Doctrine Entity - Basic Mapping with Annotations
– @Entity - tells Doctrine the class represents database table
– @Column - the property represents database column
– @Id - set property as entity primary key
– @GeneratedValue - id generation mechanism
Doctrine ORM
• Doctrine Entity
Doctrine ORM
• Doctrine Entity
– Doctrine entities should only represent database table
structure
– Do not execute SQL queries from your entities
– Do not write heavy logic in your entity classes
Doctrine DBAL
• Data Base Abstraction Layer -
built on top of PDO
ENTITY MANAGER
QueryBuilder, Persisting and Updating Entities
EntityManager
• Manage entities - persist(), remove(), flush()
– createQuery() - allows us to execute DQL queries
– createNamedQuery() - allows us to execute named DQL
queries
– createQueryBuilder() - allows us to create queries using object-
oriented approach
Entity Manager
• Doctrine Query
Language – DQL
• Very similar to SQL
• With DQL we can
update, delete, select
entities, but not persist
• With DQL we select
objects instead of table
rows
Entity Manager
• Doctrine Query Builder
• Create query in object
oriented approach
ENTITY REPOSITORY
Entity Repository, Helper Methods
Entity Repository
• Makes your code reusable
• Isolates your queries from other logic
• Provides access to helper methods for each property of
your entity
Entity Repository Class
• Automatically created when executing:
php bin/console make:entity SomeClass
• Above command will generate Doctrine Entity and empty
repository class
Entity Repository Class
• Manually Configure repository Class in your entity
Entity Repository Class
• Extending
ServiceEntityRepository
allows us to access dynamic
helper methods for each
mapped entity property
• Now you have dynamic
method names for our entity
properties without writing
single line of code
Entity Repository Class
• How to access the EntityManager in your repository class
Summary
• Doctrine ORM
• Basic entity mapping
• DBAL
• Entity Repository
25