According to the Doctrine 2 ORM Documentation on locking support:
Doctrine 2 offers support for Pessimistic- and Optimistic-locking strategies natively. This allows to take very fine-grained control over what kind of locking is required for your Entities in your application.
According to the Doctrine 2 ORM Documentation on pessimistic locking:
Doctrine 2 supports Pessimistic Locking at the database level. No attempt is being made to implement pessimistic locking inside Doctrine, rather vendor-specific and ANSI-SQL commands are used to acquire row-level locks. Every Doctrine Entity can be part of a pessimistic lock, there is no special metadata required to use this feature.
However for Pessimistic Locking to work you have to disable the Auto-Commit Mode of your Database and start a transaction around your pessimistic lock use-case using the Explicit Transaction Demarcation. Doctrine 2 will throw an Exception if you attempt to acquire an pessimistic lock and no transaction is running.
Doctrine 2 currently supports two pessimistic lock modes:
- Pessimistic Write DoctrineDBALLockMode::PESSIMISTIC_WRITE, locks the underlying database rows for concurrent Read and Write Operations.
- Pessimistic Read DoctrineDBALLockMode::PESSIMISTIC_READ, locks other concurrent requests that attempt to update or lock rows in write mode.
You can use pessimistic locks in three different scenarios:
- Using EntityManager#find($className, $id, DoctrineDBALLockMode::PESSIMISTIC_WRITE) or EntityManager#find($className, $id, DoctrineDBALLockMode::PESSIMISTIC_READ)
- Using EntityManager#lock($entity, DoctrineDBALLockMode::PESSIMISTIC_WRITE) or EntityManager#lock($entity, DoctrineDBALLockMode::PESSIMISTIC_READ)
- Using Query#setLockMode(DoctrineDBALLockMode::PESSIMISTIC_WRITE) or Query#setLockMode(DoctrineDBALLockMode::PESSIMISTIC_READ)