I'm trying to optimize my Symfony project and wondering if an entity object is being fully (all fields) fetched from the database when I pass it to a Twig template from a controller or only the fields that are being used in templates?
Let's say I have a book
entity that has title
and abstract
fields. In a controller I fetch all the book
s from the respective repository:
$books = $booksRepository->findAll();
and then pass it to a Twig template:
return $this->render('books.html.twig', [
'books' => $books
]);
Afterwards, in books.html.twig
I iterate through the books
object but using the title
field only:
{% for book in books %}
Title: {{ book.title }}<br>
{% endfor %}
I wonder if the abstract
field is also being read by Symfony from the database. Of course, it's an example and production projects may have entities with more fields. Therefore, I assume fetching unused fields on certain webpages may cause extra load to the app and database. And if the answer to my initial question is positive, I'm also curious about techniques that are used to avoid fetching unused fields.
I tried to debug the Symfony and Doctrine classes, but eventually got lost in number of classes used and couldn't find an answer to my question.
CodePudding user response:
This behavior is not related to Symfony or Twig. It is related to Doctrine 2 and the way you made your code inside Repositories.
When using $books = $booksRepository->findAll();
it will always fetch all fields.
It will be the same with all native doctrine function
find()
findOneBy()
findAll()
findBy()
If you want only a subset of field you will have to make custom repository function. For example :
$query = $this->createQueryBuilder('book')->select('book.id, book.title, book.author');
And call it instead of your findAll().
But personnally, i do not totally agree with
I assume fetching unused fields on certain webpages may cause extra load
You have to look to absolute gain value in term of ms. Most of the time for "little" entity, your query will gain 0.000xxx ms for querying only a subset of field. So i advise you to not automatically create custom repository method since load / time gain are often irrelevant and do it only when bad performance occur. It will prevent you to create a lot of code that will need to be maintain in the futur. Don't stick to a religion haha