In previous articles, we explored why the ORM consumes so much memory and how to mitigate it using chunked flush(), clear(), and toIterable(). If you’ve made it this far, you’re already convinced of the problem.
This article is the next step: how to consciously step outside the ORM when you don’t need it, without leaving the Doctrine ecosystem or breaking your project’s architecture.
The Starting Point: You Already Know the Cost
We won’t rehash why findAll() can crush your memory or why flush() with 50,000 entities takes ages. That’s already clear.
The question now is specific:
I have a query that only reads data. I’m not going to modify anything. I don’t need tracking or relationships. What should I do?
The answer is DBAL, and in this article, you’ll see exactly how to use it.
What DBAL Is and What It Isn’t
Doctrine DBAL (Database Abstraction Layer) is the layer sitting beneath the ORM. Doctrine ORM uses it internally to execute SQL, but you can also access it directly.
What DBAL gives you:
- Database connection with error handling.
- Prepared statements and secure parameter binding.
- Transaction support.
- Portability across database engines (MySQL, PostgreSQL, SQLite).
- Native Symfony integration.
What DBAL does not do:
- It does not hydrate entities.
- It does not maintain an Identity Map.
- It does not generate snapshots.
- It does not track changes.
- It does not manage relationships.
In other words: it executes SQL and returns arrays. No intermediaries.
Accessing DBAL from the EntityManager
If you already have Doctrine ORM in your project, DBAL is included. You don’t need to install anything extra:
// Desde el EntityManager (cualquier contexto)
$conn = $entityManager->getConnection();
// En Symfony, también puedes inyectarlo directamente
use Doctrine\DBAL\Connection;
class UserReadRepository
{
public function __construct(private readonly Connection $connection) {}
}
Injecting Connection directly is preferable in read repositories: it makes it explicit in the class signature that this class does not use the ORM.
Your First DBAL Query
Let’s compare the same use case using the ORM and DBAL.
With ORM (for a simple users table):
// Hidrata entidades completas, snapshots, Identity Map...
$users = $this->entityManager
->getRepository(User::class)
->findAll();
With DBAL:
$users = $this->connection->fetchAllAssociative('
SELECT id, name, email
FROM users
WHERE active = :active
ORDER BY name ASC
', ['active' => true]);
// Resultado: array de arrays asociativos
// [
// ['id' => 1, 'name' => 'Ana García', 'email' => '[email protected]'],
// ['id' => 2, 'name' => 'Luis Martínez', 'email' => '[email protected]'],
// ]
No entities, no proxies, no UnitOfWork. Just the data you requested.
The Most Useful DBAL Methods
DBAL provides several methods depending on what you need:
// Múltiples filas → array de arrays asociativos
$rows = $conn->fetchAllAssociative($sql, $params);
// Una sola fila → array asociativo (o false si no existe)
$row = $conn->fetchAssociative($sql, $params);
// Una sola columna de múltiples filas → array plano
$ids = $conn->fetchFirstColumn('SELECT id FROM users WHERE active = 1');
// Un único valor escalar
$count = $conn->fetchOne('SELECT COUNT(*) FROM users');
// Para INSERT, UPDATE, DELETE → devuelve filas afectadas
$affected = $conn->executeStatement(
'UPDATE users SET active = :active WHERE id = :id',
['active' => false, 'id' => 42]
);
DTOs: From Array to Object Without the ORM
Arrays are convenient for simple cases, but in a real-world application, you’ll want typed objects. This is where DTOs (Data Transfer Objects) come in.
A DTO for user reads:
final class UserSummaryDTO
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $email,
) {}
public static function fromRow(array $row): self
{
return new self(
id: (int) $row['id'],
name: $row['name'],
email: $row['email'],
);
}
}
And in the repository:
public function findActiveSummaries(): array
{
$rows = $this->connection->fetchAllAssociative('
SELECT id, name, email
FROM users
WHERE active = 1
ORDER BY name ASC
');
return array_map(UserSummaryDTO::fromRow(...), $rows);
}
The result is an array of typed objects, without Doctrine hydration, without tracking, with IDE autocompletion, and with zero memory surprises.
More Complex Queries: Where DBAL Truly Shines
The ORM starts to creak when queries get complicated. DBAL, on the other hand, scales naturally:
public function getOrderStats(\DateTimeImmutable $from, \DateTimeImmutable $to): array
{
return $this->connection->fetchAllAssociative('
SELECT
DATE(o.created_at) AS day,
COUNT(o.id) AS total_orders,
SUM(o.total) AS revenue,
AVG(o.total) AS avg_order_value,
COUNT(DISTINCT o.user_id) AS unique_customers
FROM orders o
WHERE o.created_at BETWEEN :from AND :to
AND o.status = :status
GROUP BY DATE(o.created_at)
ORDER BY day DESC
', [
'from' => $from->format('Y-m-d'),
'to' => $to->format('Y-m-d'),
'status' => 'completed',
]);
}
Trying to express this with DQL and entities would not only be more verbose—it would be slower, harder to optimize, and harder to read.
The Hybrid Repository Pattern
Here is the architectural core of this article.
The idea is simple: a write repository with the ORM, a read repository with DBAL. Both coexist in the same project, each specialized in what it does best.
Write Repository (ORM)
final class UserRepository
{
public function __construct(
private readonly EntityManagerInterface $entityManager,
) {}
public function save(User $user): void
{
$this->entityManager->persist($user);
$this->entityManager->flush();
}
public function findById(int $id): ?User
{
return $this->entityManager->find(User::class, $id);
}
public function remove(User $user): void
{
$this->entityManager->remove($user);
$this->entityManager->flush();
}
}
This repository works with real entities. It handles tracking, cascades, and lifecycle events. This is where the ORM delivers its maximum value.
Read Repository (DBAL)
final class UserReadRepository
{
public function __construct(
private readonly Connection $connection,
) {}
public function findActiveSummaries(): array
{
$rows = $this->connection->fetchAllAssociative('
SELECT id, name, email
FROM users
WHERE active = 1
ORDER BY name ASC
');
return array_map(UserSummaryDTO::fromRow(...), $rows);
}
public function findWithOrderStats(int $userId): ?UserStatsDTO
{
$row = $this->connection->fetchAssociative('
SELECT
u.id,
u.name,
u.email,
COUNT(o.id) AS total_orders,
SUM(o.total) AS total_spent
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE u.id = :id
GROUP BY u.id
', ['id' => $userId]);
return $row ? UserStatsDTO::fromRow($row) : null;
}
public function countActiveByCountry(): array
{
return $this->connection->fetchAllAssociative('
SELECT country, COUNT(*) AS total
FROM users
WHERE active = 1
GROUP BY country
ORDER BY total DESC
');
}
}
This repository doesn’t even know that a User entity exists. It only knows how to write efficient SQL and return data.
How They Coexist in a Service
final class UserService
{
public function __construct(
private readonly UserRepository $users, // ORM: writes
private readonly UserReadRepository $userReads, // DBAL: reads
) {}
// Escritura → ORM
public function register(string $name, string $email): void
{
$user = new User($name, $email);
$this->users->save($user);
}
// Lectura simple → DBAL
public function getActiveSummaries(): array
{
return $this->userReads->findActiveSummaries();
}
// Lectura con lógica de negocio → ORM
public function deactivate(int $userId): void
{
$user = $this->users->findById($userId);
$user->deactivate(); // lógica de dominio en la entidad
$this->users->save($user);
}
}
The rule is straightforward: if the operation modifies state or requires domain logic, use the ORM repository. If it only reads data for display, use the DBAL repository.
DBAL QueryBuilder: Dynamic SQL Without String Concatenation
When filters are dynamic (searches, pagination, variable sorting), DBAL provides its own QueryBuilder, which is lighter than the ORM’s:
public function search(UserSearchCriteria $criteria): array
{
$qb = $this->connection->createQueryBuilder()
->select('id', 'name', 'email', 'created_at')
->from('users')
->where('active = :active')
->setParameter('active', true)
->orderBy('name', 'ASC')
->setMaxResults($criteria->limit)
->setFirstResult($criteria->offset);
if ($criteria->country !== null) {
$qb->andWhere('country = :country')
->setParameter('country', $criteria->country);
}
if ($criteria->search !== null) {
$qb->andWhere('name LIKE :search OR email LIKE :search')
->setParameter('search', '%' . $criteria->search . '%');
}
return array_map(
UserSummaryDTO::fromRow(...),
$qb->fetchAllAssociative()
);
}
No string concatenation, no SQL injection risk, none of the ORM’s overhead.
Transactions with DBAL
DBAL also handles transactions, which is crucial when you need atomicity for write operations that bypass the ORM:
public function transferCredits(int $fromId, int $toId, int $amount): void
{
$this->connection->transactional(function (Connection $conn) use ($fromId, $toId, $amount): void {
$conn->executeStatement(
'UPDATE accounts SET credits = credits - :amount WHERE id = :id',
['amount' => $amount, 'id' => $fromId]
);
$conn->executeStatement(
'UPDATE accounts SET credits = credits + :amount WHERE id = :id',
['amount' => $amount, 'id' => $toId]
);
});
}
If either operation fails, the transaction is automatically rolled back.
When to Use Each Tool: A Quick Guide
| Situation | Tool |
|---|---|
| Create, update, or delete entities | ORM |
| Domain logic (invariants, business rules) | ORM |
| Complex relationships with cascades | ORM |
| Reading data for an API or listing | DBAL |
| Dashboards, reports, analytics | DBAL |
| Aggregations (COUNT, SUM, AVG) | DBAL |
| Bulk exports | DBAL + toIterable() |
| Queries with multiple JOINs without domain logic | DBAL |
| ETL or batch read processing | DBAL |
What We Gain from This Separation
To understand the real impact, let’s see what happens when querying 10,000 users with three simple columns (id, name, email) in a table without relationships. The numbers are illustrative but represent realistic proportions you can reproduce in any medium-sized project:
| Metric | ORM (findAll()) | DBAL (fetchAllAssociative) | Difference |
|---|---|---|---|
| Peak memory | ~85 MB | ~8 MB | ~10× less |
| Execution time | ~620 ms | ~55 ms | ~11× faster |
| In-memory objects | ~10,000 entities + proxies + snapshots | ~10,000 simple arrays | No UoW overhead |
| ORM work | Hydration, Identity Map, UnitOfWork, snapshots | None | — |
The memory difference comes from what Doctrine builds for every entity: the object instance, a snapshot copy to detect changes, the Identity Map entry, and, if there are relationships, additional proxies. With DBAL, a row is simply a PHP associative array. Nothing more.
The multiplier worsens with relationships. If User had an EAGER relationship with Address, the ORM would also hydrate 10,000 Address objects. DBAL only returns what the SELECT explicitly asks for.
The difference is magnified in exports and workers. In a process that iterates over 100,000 records, switching from ORM to DBAL can be the difference between a worker crashing due to memory limits and one finishing without incident.
Beyond the numbers:
Readability: SQL lives where it makes sense and is easy to audit, optimize with EXPLAIN, or hand off to a DBA.
Architectural clarity: when someone reads UserReadRepository, they immediately know that this class will never mutate data. The intention is right there in the signature.
It’s Not ORM vs SQL: It’s the Right Tool for the Job
Doctrine ORM remains an excellent tool for what it was designed for: persisting and retrieving domain objects with state, relationships, and behavior.
The problem was never the ORM. The problem is using it for absolutely everything, including scenarios where you just need to read data and return it.
The hybrid pattern—ORM for writes and domain logic, DBAL for reads—doesn’t require overengineering or rewriting the project. You can introduce it incrementally: next time you have an expensive read query, extract it into a DBAL repository. Measure the difference. From there, decide how far to take the pattern.
Scaling an application often doesn’t mean swapping databases or adding a cache layer. It means stopping unnecessary work before it reaches them.
Frequently Asked Questions
Can I use DBAL and ORM within the same transaction?
Yes. They share the same underlying connection, so ORM and DBAL operations can participate in the same transaction:
$this->entityManager->beginTransaction();
try {
$this->entityManager->persist($entity);
$this->entityManager->flush();
$this->connection->executeStatement('UPDATE stats SET total = total + 1');
$this->entityManager->commit();
} catch (\Throwable $e) {
$this->entityManager->rollback();
throw $e;
}
Does DBAL protect against SQL injection?
Yes, provided you use named parameters like :name or positional ? placeholders and never concatenate values directly into the SQL string. DBAL’s fetchAllAssociative, executeStatement, and QueryBuilder methods use prepared statements internally.
Do I need to install anything extra for DBAL?
No. If you have doctrine/orm in your project, doctrine/dbal is already included as a dependency. You only need to inject Doctrine\DBAL\Connection into your class.