Slide 1

Slide 1 text

OBJECT RELATIONAL WHAT? Denis Brumann
 @dbrumann
 [email protected]

Slide 2

Slide 2 text

DENIS BRUMANN [email protected] 
 @dbrumann SOFTWARE DEVELOPER BERLIN, GERMANY

Slide 3

Slide 3 text

Denis Brumann
 @dbrumann
 [email protected] !3 DATA MAPPER

Slide 4

Slide 4 text

Denis Brumann
 @dbrumann
 [email protected] !4

Slide 5

Slide 5 text

Denis Brumann
 @dbrumann
 [email protected] !5 /** * @ORM\Entity(repositoryClass="App\Repository\RentalZoneRepository") * @ORM\Table(name="carsharing_rental_zone") */ class RentalZone { /** * @ORM\Id() * @ORM\Column(name="hal_id", type="integer") * @ORM\GeneratedValue(strategy="NONE") */ private $id; /** * @ORM\Column(name="hal_src", type="string", length=16) */ private $source;

Slide 6

Slide 6 text

Denis Brumann
 @dbrumann
 [email protected] /** * @ORM\Embedded(class="App\Entity\Coordinates",
 * columnPrefix=false) */ private $coordinates; !6

Slide 7

Slide 7 text

Denis Brumann
 @dbrumann
 [email protected] /** * @ORM\Embeddable() */ class Coordinates { /** * @ORM\Column(name="latitude", type="decimal", precision=18, scale=15, nullable=true) */ private $latitude; /** * @ORM\Column(name="longitude", type="decimal", precision=18, scale=15, nullable=true) */ private $longitude; } !6

Slide 8

Slide 8 text

Denis Brumann
 @dbrumann
 [email protected] !7 interface ObjectManager { public function find($className, $id); public function persist($object); public function remove($object); public function merge($object); public function clear($objectName = null); public function detach($object); public function refresh($object); public function flush(); public function getRepository($className); public function getClassMetadata($className); public function getMetadataFactory(); public function initializeObject($obj); public function contains($object); } QUERYING

Slide 9

Slide 9 text

Denis Brumann
 @dbrumann
 [email protected] !7 interface ObjectManager { public function find($className, $id); public function persist($object); public function remove($object); public function merge($object); public function clear($objectName = null); public function detach($object); public function refresh($object); public function flush(); public function getRepository($className); public function getClassMetadata($className); public function getMetadataFactory(); public function initializeObject($obj); public function contains($object); } QUERYING OBJECT HYDRATION

Slide 10

Slide 10 text

Denis Brumann
 @dbrumann
 [email protected] !7 interface ObjectManager { public function find($className, $id); public function persist($object); public function remove($object); public function merge($object); public function clear($objectName = null); public function detach($object); public function refresh($object); public function flush(); public function getRepository($className); public function getClassMetadata($className); public function getMetadataFactory(); public function initializeObject($obj); public function contains($object); } QUERYING OBJECT HYDRATION STATE

Slide 11

Slide 11 text

Denis Brumann
 @dbrumann
 [email protected] !7 interface ObjectManager { public function find($className, $id); public function persist($object); public function remove($object); public function merge($object); public function clear($objectName = null); public function detach($object); public function refresh($object); public function flush(); public function getRepository($className); public function getClassMetadata($className); public function getMetadataFactory(); public function initializeObject($obj); public function contains($object); } QUERYING OBJECT HYDRATION STATE "TRANSACTIONS"

Slide 12

Slide 12 text

Denis Brumann
 @dbrumann
 [email protected] !8

Slide 13

Slide 13 text

/** * Finds an Entity by its identifier. * * @param string $entityName The class name of the entity to find. * @param mixed $id The identity of the entity to find. * @param integer|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants * or NULL if no specific lock mode should be used * during the search. * @param integer|null $lockVersion The version of the entity to find when using * optimistic locking. * * @return object|null The entity instance or NULL if the entity can not be found. * * @throws OptimisticLockException * @throws ORMInvalidArgumentException * @throws TransactionRequiredException * @throws ORMException */ public function find($entityName, $id, $lockMode = null, $lockVersion = null) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); if ($lockMode !== null) { $this->checkLockRequirements($lockMode, $class); } if ( ! is_array($id)) { if ($class->isIdentifierComposite) { throw ORMInvalidArgumentException::invalidCompositeIdentifier(); }

Slide 14

Slide 14 text

public function find($entityName, $id, $lockMode = null, $lockVersion = null) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); if ($lockMode !== null) { $this->checkLockRequirements($lockMode, $class); } if ( ! is_array($id)) { if ($class->isIdentifierComposite) { throw ORMInvalidArgumentException::invalidCompositeIdentifier(); } $id = [$class->identifier[0] => $id]; } foreach ($id as $i => $value) { if (is_object($value) && $this->metadataFactory- >hasMetadataFor(ClassUtils::getClass($value))) { $id[$i] = $this->unitOfWork->getSingleIdentifierValue($value); if ($id[$i] === null) { throw ORMInvalidArgumentException::invalidIdentifierBindingEntity(); } } } $sortedId = []; foreach ($class->identifier as $identifier) {

Slide 15

Slide 15 text

throw ORMException::missingIdentifierField($class->name, $identifier); } $sortedId[$identifier] = $id[$identifier]; unset($id[$identifier]); } if ($id) { throw ORMException::unrecognizedIdentifierFields($class->name, array_keys($id)); } $unitOfWork = $this->getUnitOfWork(); // Check identity map first if (($entity = $unitOfWork->tryGetById($sortedId, $class->rootEntityName)) !== false) { if ( ! ($entity instanceof $class->name)) { return null; } switch (true) { case LockMode::OPTIMISTIC === $lockMode: $this->lock($entity, $lockMode, $lockVersion); break; case LockMode::NONE === $lockMode: case LockMode::PESSIMISTIC_READ === $lockMode: case LockMode::PESSIMISTIC_WRITE === $lockMode: $persister = $unitOfWork->getEntityPersister($class->name); $persister->refresh($sortedId, $entity, $lockMode);

Slide 16

Slide 16 text

case LockMode::NONE === $lockMode: case LockMode::PESSIMISTIC_READ === $lockMode: case LockMode::PESSIMISTIC_WRITE === $lockMode: $persister = $unitOfWork->getEntityPersister($class->name); $persister->refresh($sortedId, $entity, $lockMode); break; } return $entity; // Hit! } $persister = $unitOfWork->getEntityPersister($class->name); switch (true) { case LockMode::OPTIMISTIC === $lockMode: $entity = $persister->load($sortedId); $unitOfWork->lock($entity, $lockMode, $lockVersion); return $entity; case LockMode::PESSIMISTIC_READ === $lockMode: case LockMode::PESSIMISTIC_WRITE === $lockMode: return $persister->load($sortedId, null, null, [], $lockMode); default: return $persister->loadById($sortedId); } }

Slide 17

Slide 17 text

Denis Brumann
 @dbrumann
 [email protected] !10

Slide 18

Slide 18 text

Denis Brumann
 @dbrumann
 [email protected] !10

Slide 19

Slide 19 text

Denis Brumann
 @dbrumann
 [email protected] !10

Slide 20

Slide 20 text

Denis Brumann
 @dbrumann
 [email protected] !10

Slide 21

Slide 21 text

Denis Brumann
 @dbrumann
 [email protected] !11 UNIT OF WORK

Slide 22

Slide 22 text

Denis Brumann
 @dbrumann
 [email protected] !12 UNIT OF WORK A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

Slide 23

Slide 23 text

Denis Brumann
 @dbrumann
 [email protected] !13 public function checkout(array $cartItems): void { $order = new Order(); foreach ($cartItems as $cartItem) { $orderItem = new OrderItem(); $orderItem->setName($cartItem->getName()); $orderItem->setPrice($cartItem->getPrice()); $order->addItem($orderItem); } $this->manager->persist($order); $this->manager->flush(); }

Slide 24

Slide 24 text

Denis Brumann
 @dbrumann
 [email protected] !14

Slide 25

Slide 25 text

Denis Brumann
 @dbrumann
 [email protected] !14

Slide 26

Slide 26 text

Denis Brumann
 @dbrumann
 [email protected] !14

Slide 27

Slide 27 text

Denis Brumann
 @dbrumann
 [email protected] !15

Slide 28

Slide 28 text

Denis Brumann
 @dbrumann
 [email protected] !16 public function checkout(array $cartItems): void { $order = new Order(); foreach ($cartItems as $cartItem) { $orderItem = new OrderItem(); $orderItem->setName($cartItem->getName()); $orderItem->setPrice($cartItem->getPrice()); $order->addItem($orderItem); $this->manager->persist($orderItem); } $this->manager->persist($order); $this->manager->flush(); }

Slide 29

Slide 29 text

use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="App\Repository\OrderRepository") * @ORM\Table(name="app_order") */ class Order { /** * @ORM\Id() * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\OneToMany(targetEntity="App\Entity\OrderItem", mappedBy="order", cascade={"persist"}) */ private $items; /** * @ORM\Column(type="datetime_immutable") */ private $createdOn; public function __construct() {

Slide 30

Slide 30 text

Denis Brumann
 @dbrumann
 [email protected] !18 CHANGE SETS Computes all the changes that have been done to entities and collections since the last commit and stores these changes in the $entityChangeSet map temporarily for access by the persisters, until the UoW commit is finished.

Slide 31

Slide 31 text

No content

Slide 32

Slide 32 text

{ "00000000085bc321000000004502eb13": { "createdOn": [
 null,
 {
 "date": "2018-12-20 20:49:32.824391",
 "timezone_type": 3,
 "timezone": "Europe\/Berlin"
 }
 ] }, "00000000085bc37e000000004502eb13": { "status": [null, 0], "name": [null, "Chewing gums"], "price": [null, "249"], "order": [null, {App\Entity\Order}] } } Order OrderItem

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

Doctrine ORM does not save unintentionally persisted entities. You have to add cascade to the association or persist each object manually. Only entities managed by the UnitOfWork will be inserted.

Slide 36

Slide 36 text

Denis Brumann
 @dbrumann
 [email protected] !24 $this->entityManager->flush($order); !

Slide 37

Slide 37 text

No content

Slide 38

Slide 38 text

No content

Slide 39

Slide 39 text

$oid = spl_object_hash($entity)

Slide 40

Slide 40 text

$oid = spl_object_hash($entity) This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects.

Slide 41

Slide 41 text

$oid = "00000000600cd8330000000053755686"

Slide 42

Slide 42 text

Inside the UnitOfWork entities are identified by their object hash, not their primary key.

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

$item = new OrderItem(); $item->setName('Socks'); $item->setPrice('999'); $manager->persist($item); $order = new Order(); $order->addItem($item); $manager->persist($order); $manager->flush();

Slide 45

Slide 45 text

$item = new OrderItem(); $item->setName('Socks'); $item->setPrice('999'); $manager->persist($item); $order = new Order(); $order->addItem($item); $manager->persist($order); $manager->flush();

Slide 46

Slide 46 text

$item = new OrderItem(); $item->setName('Socks'); $item->setPrice('999'); $manager->persist($item); $order = new Order(); $order->addItem($item); $manager->persist($order); $manager->flush();

Slide 47

Slide 47 text

UnitOfWork will take care of correctly ordering each commit. You can persist your entities in any order you like.

Slide 48

Slide 48 text

Denis Brumann
 @dbrumann
 [email protected] !31

Slide 49

Slide 49 text

{% extends "base.html.twig" %} {% block body %}

Order list

{% endblock %}


 contains {{ order.items|length }} items for a total of
 {{ order.total / 100 }}€.

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

Denis Brumann
 @dbrumann
 [email protected] !34 1 QUERY TO FETCH ALL ORDERS

Slide 52

Slide 52 text

Denis Brumann
 @dbrumann
 [email protected] !34 1 QUERY TO FETCH ALL ORDERS + 1 QUERY/ORDER
 TO FETCH ITEMS

Slide 53

Slide 53 text

No content

Slide 54

Slide 54 text

Denis Brumann
 @dbrumann
 [email protected] !39

Slide 55

Slide 55 text

Denis Brumann
 @dbrumann
 [email protected] !40

Slide 56

Slide 56 text

Denis Brumann
 @dbrumann
 [email protected] !41 public function findOrderWithItems(int $id) { return $this->createQueryBuilder('o') ->select(['o', 'i']) ->where('o.id = :order_id') ->setParameter('order_id', $id) ->join('o.items', 'i') ->getQuery() ->getSingleResult(); }

Slide 57

Slide 57 text

Denis Brumann
 @dbrumann
 [email protected] !41 public function findOrderWithItems(int $id) { return $this->createQueryBuilder('o') ->select(['o', 'i']) ->where('o.id = :order_id') ->setParameter('order_id', $id) ->join('o.items', 'i') ->getQuery() ->getSingleResult(); }

Slide 58

Slide 58 text

Denis Brumann
 @dbrumann
 [email protected] !41 public function findOrderWithItems(int $id) { return $this->createQueryBuilder('o') ->select(['o', 'i']) ->where('o.id = :order_id') ->setParameter('order_id', $id) ->join('o.items', 'i') ->getQuery() ->getSingleResult(); }

Slide 59

Slide 59 text

Denis Brumann
 @dbrumann
 [email protected] !42 CUSTOM OBJECT HYDRATION

Slide 60

Slide 60 text

Denis Brumann
 @dbrumann
 [email protected] !43 public function findSummarizedOrders(): array { $dql = 'SELECT NEW App\\DTO\\OrderSummary(
 o.id, o.createdOn, COUNT(i.order), SUM(i.price) ) FROM App\\Entity\\Order o JOIN o.items i GROUP BY i.order'; return $this->getEntityManager() ->createQuery($dql) ->getResult(); }

Slide 61

Slide 61 text

Denis Brumann
 @dbrumann
 [email protected] !44 SELECT o.id, o.created_on, COUNT(i.order_id), SUM(i.price) FROM app_order AS o JOIN app_order_item i on o.id = i.order_id GROUP BY o.id ORDER BY o.created_on ASC

Slide 62

Slide 62 text

orderId = $orderId; $this->orderDate = $orderDate; $this->itemCount = $itemCount; $this->total = $total; } public function getOrderId(): int { return $this->orderId; } public function getOrderDate(): DateTimeImmutable { return $this->orderDate;

Slide 63

Slide 63 text

public function __construct(int $orderId, DateTimeImmutable $orderDate, int $itemCount, int $total) { $this->orderId = $orderId; $this->orderDate = $orderDate; $this->itemCount = $itemCount; $this->total = $total; } public function getOrderId(): int { return $this->orderId; } public function getOrderDate(): DateTimeImmutable { return $this->orderDate; } public function getItemCount(): int { return $this->itemCount; } public function getTotal(): int { return $this->total; } }

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

No content

Slide 66

Slide 66 text

public function findMostExpensiveOrder(): ?Order { $sql = <<getEntityManager()); $resultSetMapping->addRootEntityFromClassMetadata(Order::class, 'o'); return $this->getEntityManager() ->createNativeQuery($sql, $resultSetMapping) ->getOneOrNullResult(); }

Slide 67

Slide 67 text

Denis Brumann
 @dbrumann
 [email protected] !48 FETCH MODE

Slide 68

Slide 68 text

/** * @ORM\Entity(repositoryClass="App\Repository\OrderReposi ") * @ORM\Table(name="app_order") */ class Order { /** * @ORM\Id() * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\OneToMany( * targetEntity="App\Entity\OrderItem", * mappedBy="order", * cascade={"persist"}, * fetch="EAGER" * ) */

Slide 69

Slide 69 text

Doctrine loads associated entities lazily by default. Writing custom queries with JOIN, custom DTO- Results or scalar results can improve read- performance.

Slide 70

Slide 70 text

* @param integer|null $lockMode One of the \Doctrine\DBAL\LockMode::* constants * or NULL if no specific lock mode should be used * during the search. * @param integer|null $lockVersion The version of the entity to find when using * optimistic locking. * * @return object|null The entity instance or NULL if the entity can not be found. * * @throws OptimisticLockException * @throws ORMInvalidArgumentException * @throws TransactionRequiredException * @throws ORMException */ public function find($entityName, $id, $lockMode = null, $lockVersion = null) { $class = $this->metadataFactory->getMetadataFor(ltrim($entityName, '\\')); if ($lockMode !== null) { $this->checkLockRequirements($lockMode, $class); } if ( ! is_array($id)) { if ($class->isIdentifierComposite) { throw ORMInvalidArgumentException::invalidCompositeIdentifier(); } $id = [$class->identifier[0] => $id]; } foreach ($id as $i => $value) {

Slide 71

Slide 71 text

Denis Brumann
 @dbrumann
 [email protected] !52

Slide 72

Slide 72 text

Denis Brumann
 @dbrumann
 [email protected] !53 $order = $this->em->find(Order::class, 1); dump($this->em->getUnitOfWork()->getIdentityMap()); $sameOrder = $this->em->find(Order::class, 1); dump($order === $sameOrder);

Slide 73

Slide 73 text

Denis Brumann
 @dbrumann
 [email protected] !53 $order = $this->em->find(Order::class, 1); dump($this->em->getUnitOfWork()->getIdentityMap()); $sameOrder = $this->em->find(Order::class, 1); dump($order === $sameOrder);

Slide 74

Slide 74 text

Denis Brumann
 @dbrumann
 [email protected] !53 $order = $this->em->find(Order::class, 1); dump($this->em->getUnitOfWork()->getIdentityMap()); $sameOrder = $this->em->find(Order::class, 1); dump($order === $sameOrder);

Slide 75

Slide 75 text

Denis Brumann
 @dbrumann
 [email protected] !54

Slide 76

Slide 76 text

Denis Brumann
 @dbrumann
 [email protected] !54

Slide 77

Slide 77 text

Denis Brumann
 @dbrumann
 [email protected] !54

Slide 78

Slide 78 text

Denis Brumann
 @dbrumann
 [email protected] !55 $order = $this->repository->find(1); !

Slide 79

Slide 79 text

Doctrine keeps an Identity Map referencing each known entity. When an entity is already known Doctrine does refrain from querying the database for it (sometimes) .

Slide 80

Slide 80 text

Denis Brumann
 @dbrumann
 [email protected] !57 $item = new OrderItem(); $item->setName('Coffee'); $item->setPrice('149'); $order = new Order(); $order->setId(1); $order->addItem($item); $this->manager->flush();

Slide 81

Slide 81 text

Denis Brumann
 @dbrumann
 [email protected] !58 $item = new OrderItem(); $item->setName('Coffee'); $item->setPrice('149'); $order = new Order(); $order->setId(1); $order->addItem($item); $this->manager->flush(); WILL THIS UPDATE THE EXISTING ORDER?

Slide 82

Slide 82 text

ENTITY STATES A NEW entity instance has no persistent identity, and is not yet associated with an EntityManager and a UnitOfWork (i.e. those just created with the "new" operator).

Slide 83

Slide 83 text

A MANAGED entity instance is an instance with a persistent identity that is associated with an EntityManager and whose persistence is thus managed. ENTITY STATES

Slide 84

Slide 84 text

A DETACHED entity instance is an instance with a persistent identity that is not (or no longer) associated with an EntityManager and a UnitOfWork. ENTITY STATES

Slide 85

Slide 85 text

A REMOVED entity instance is an instance with a persistent identity, associated with an EntityManager, that will be removed from the database upon transaction commit. ENTITY STATES

Slide 86

Slide 86 text

Denis Brumann
 @dbrumann
 [email protected] !63 STATE

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

No content

Slide 89

Slide 89 text

No content

Slide 90

Slide 90 text

$order = new Order(); $order->setId(1); $this->entityManager->flush();

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

When Doctrine saves a new entity when you want to update or vice versa, check the UnitOfWork's entityInsertions and entityUpdates. Make sure to do this during flush as this is when the associatedEntities are collected at the very latest. !

Slide 93

Slide 93 text

Denis Brumann
 @dbrumann
 [email protected] !68 MERGE & DETACH

Slide 94

Slide 94 text

Denis Brumann
 @dbrumann
 [email protected] !69 public function __construct(SessionInterface $session, EntityManagerInterface $entityManager) { $this->session = $session; $this->entityManager = $entityManager; } public function loadUser(): ?User { if ($this->session->has('user')) { // Loads User-entity stored in session and merges it into the UnitOfWork return $this->entityManager->merge($this->session->get('user')); } return null; }

Slide 95

Slide 95 text

Denis Brumann
 @dbrumann
 [email protected] !70 API Client App fetch Order with ID 2 EntityManager::find(Order, 2) returns Order data as JSON

Slide 96

Slide 96 text

Denis Brumann
 @dbrumann
 [email protected] !70 API Client App fetch Order with ID 2 EntityManager::find(Order, 2) returns Order data as JSON

Slide 97

Slide 97 text

Denis Brumann
 @dbrumann
 [email protected] !71 API Client App patch Order with ID 2
 (passes Order data as JSON)

Slide 98

Slide 98 text

Denis Brumann
 @dbrumann
 [email protected] !73 $patch = $this->serializer->deserialize( $request->getContent(), Order::class, 'json' ); $updatedOrder = $this->entityManager->merge($patch); $this->entityManager->flush();

Slide 99

Slide 99 text

Denis Brumann
 @dbrumann
 [email protected] !74 DON'T

Slide 100

Slide 100 text

Doctrine 3 will no longer support merge and detach. Instead of merging through the EntityManager, do a find and then update the entity manually. Instead of detaching an entity, you can just clear the EntityManager. !

Slide 101

Slide 101 text

Denis Brumann
 @dbrumann
 [email protected] !76 FLUSH($ENTITY) ENTITYMANAGER->MERGE($ENTITY) REMOVED IN DOCTRINE 3 ENTITYMANAGER->DETACH($ENTITY)