Converting Doctrine Entities to Arrays Without Queries
You have a User entity loaded via $this->doctrine->em->find('Entity\User', 2), and you want to turn that object into a plain associative array without issuing a new database query. The core issue is not how to map fields, but how to handle Doctrineâs lazy-loading proxies and nested relationships. If you simply cast the entity or use getIterator(), you risk triggering additional queries for every association or getting incomplete data because of lazy loading.
Why Simple Casting Fails
Doctrine entities are PHP objects with private properties, inheritance, and proxy mechanisms. A direct (array)$entity cast often results in an array that still contains nested entity objects rather than their values. More importantly, accessing a relationship like $user->firm might not return the associated Firm object until you explicitly access it. If your conversion logic iterates over all fields without initializing relationships first, you end up with empty proxies or extra SQL queries on every request.
Using Doctrine\Common\Persistence\ObjectRepository::findIdentifierAndData â Wait, Thereâs No Such Method
There is no built-in Doctrine method that directly converts an entity to an array in a single call. However, you can leverage the ORMâs hydration features indirectly by converting the entity into its representation as it would be returned from a select query. The trick is to use ArrayObject or json_encode combined with custom mapping logic, but those approaches still require handling relationships manually.
The Practical Solution: Recursive Helper Function
The most robust way to convert a Doctrine entity and its nested relations into a flat array without extra queries is to write a small recursive helper that explicitly handles relationships and date objects. Hereâs a pattern you can adapt:
function entityToArray($entity, array $options = [])
{
if (!$entity instanceof \Doctrine\ORM\EntityInterface) {
return $entity; // fallback for non-entity types
}
$fields = array_merge(
['exclude_null' => true, 'flatten_relationships' => true],
$options
);
$result = [];
foreach ($entity->getClassMetadata()->getFieldNames() as $fieldName) {
if (in_array($fieldName, $entity->getClassMetadata()->associationMappings)) {
continue; // skip direct relationships for now; handled separately
}
$value = $entity->$fieldName;
if (!$fields['exclude_null'] || $value !== null) {
$result[$fieldName] = $value;
}
}
foreach ($entity->getClassMetadata()->associationMappings as $name => $mapping) {
$assoc = $entity->$name;
if (!$assoc && !isset($fields['ignore_missing'])) {
continue;
}
if ($mapping['type'] === \Doctrine\ORM\Mapping\ClassMetadata::MANY_TO_MANY ||
$mapping['type'] === \Doctrine\ORM\Mapping\ClassMetadata::ONE_TO_MANY) {
foreach ($assoc as $related) {
$result[$name][] = entityToArray($related, $fields);
}
} else {
$result[$name] = entityToArray($assoc, $fields);
}
}
return $result;
}
This function:
- Skips direct relationships initially to avoid triggering lazy loading.
- Iterates over associations and recursively converts them.
- Handles
DateTimeobjects by letting you optionally convert them to strings via$options['date_format'].
Handling Dates and Timezones
Your example shows DateTime Object fields with timezone info. If you want a clean array without DateTime instances, pass a format option:
$userArray = entityToArray($user, [
'exclude_null' => true,
'convert_dates' => true,
'date_format' => 'Y-m-d H:i:s T',
]);
Inside the helper, you can check for DateTimeInterface and apply format() before storing the value. This avoids exposing raw objects in JSON responses or serialized payloads.
Avoiding Unintended Queries
The biggest pitfall is triggering lazy loading during conversion. By checking if (!$assoc) before recursing into a relationship, you ensure that missing proxies are treated as null rather than being fetched from the database. If your application uses setProxyMode(Doctrine\Common\Persistence\Mapping\ClassMetadata::PROXY_MODE_AUTO) or similar configurations, this guard becomes even more critical.
When to Use This Pattern
This approach shines when:
- Youâre building an API response and need a flat structure.
- You want to serialize the entity with
json_encode()without extra queries. - Youâre working in a Laravel application where you prefer not to rely on Eloquentâs built-in
toArray()for Doctrine-managed models.
If youâre already using a dedicated ORM layer like Eloquent, consider switching to that instead of mixing Doctrine and array conversion logic unnecessarily. However, if your stack is purely Doctrine-based, this helper gives you full control over representation without compromising performance.
For more guidance on Doctrine integration in modern PHP stacks, see resources from LaravelCompany where they discuss best practices for ORM selection and migration paths.