How does the doctrine entity management flush () method work?

The Doctrine Documentation has this code:

<?php // update_product.php <id> <new-name> require_once "bootstrap.php"; $id = $argv[1]; $newName = $argv[2]; $product = $entityManager->find('Product', $id); if ($product === null) { echo "Product $id does not exist.\n"; exit(1); } $product->setName($newName); $entityManager->flush(); 

What I don't understand is the last part, where after setting the product name using $product->setName() , the $entityManager->flush() method is called:

 $product->setName($newName); $entityManager->flush(); 

It seems to me that there is no connection between the $product variable and the $entityManager variable, except for the fact that $product must contain the response from the $entityManager->find() method.

How is it possible that $entityManager->flush() can read the values ​​set by $product->setName() ?

+5
source share
3 answers

All of the above answers are good, but the real answer is that, by PHP5, objects are passed by default by reference, and in PHP4 they are passed by value.

This is why the code in the example above works.

Here are the details: http://php.net/manual/en/language.oop5.references.php

-1
source

Doctrine uses the Identity Map template to track objects. Whenever you pull an object from the database, Doctrine will keep a reference to that object inside UnitOfWork . An array containing all the link objects is two-level and has the keys "root object name" and "I would". Because Doctrine allows you to create composite keys, the identifier is sorted, a serialized version of all key columns.

http://doctrine-orm.readthedocs.org/en/latest/reference/unitofwork.html

And you can ask how it can read / write values ​​for the object, because, well, they are protected (they should, if you follow the user manual)!

It's simple, Doctrine uses reflection .

An interesting method from UnityOfWork that calculates if there are any changes to objects: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/UnitOfWork.php#L560

+4
source

This is a ORM magic :)

But seriously, when you retrieve your data using Doctrine , it adds a lot of metadata to your objects. You can view these fields yourself, just a var_dump() object.

When you do flush() , Doctrine checks all the fields of all the selected data and makes a transaction in the database.

When you initialize a new object, it does not have Doctrine metadata, so you need to call another persist() method to add it.

You can also just look at the source code of EntityManager to better understand how it works - Doctrine is an open source project.

+2
source

Source: https://habr.com/ru/post/1211725/


All Articles