PHPackages                             tourze/doctrine-entity-lock-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. tourze/doctrine-entity-lock-bundle

ActiveLibrary[Database &amp; ORM](/categories/database)

tourze/doctrine-entity-lock-bundle
==================================

为 Doctrine 实体提供自动锁定和刷新机制

1.0.1(4mo ago)08623MITPHPCI passing

Since Apr 15Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/tourze/doctrine-entity-lock-bundle)[ Packagist](https://packagist.org/packages/tourze/doctrine-entity-lock-bundle)[ RSS](/packages/tourze-doctrine-entity-lock-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (4)Dependencies (18)Versions (5)Used By (3)

Doctrine Entity Lock Bundle
===========================

[](#doctrine-entity-lock-bundle)

[![PHP Version](https://camo.githubusercontent.com/04744bae0a61d2ffe29c26f07a9612eae20445fc6feaeb77b3af1f0e9be6447c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f7068702d253345253344382e312d3838393242462e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/7013272bd27ece47364536a221edb554cd69683b68a46fc0ee96881174c4214c/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d626c75652e737667)](LICENSE)![Build Status](https://camo.githubusercontent.com/c27a457659b89ee4f1f80f7995c559dd37f2051bde7167ad25791e5c5c92cc8e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6275696c642d70617373696e672d627269676874677265656e2e737667)![Coverage Status](https://camo.githubusercontent.com/b3545ae1bcdb4ea486f71f87b43001e82dd21933bc8035d44601706c851265da/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e2e737667)

[English](README.md) | [中文](README.zh-CN.md)

This Symfony Bundle provides a simple way to apply distributed locking mechanisms to Doctrine entities for handling concurrent operations.

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Installation](#installation)
- [Usage](#usage)
    - [Prerequisites](#prerequisites)
    - [Locking Single Entity](#locking-single-entity)
    - [Locking Multiple Entities](#locking-multiple-entities)
- [Testing](#testing)
- [Configuration](#configuration)
    - [Custom Lock Timeout](#custom-lock-timeout)
    - [Custom Lock Store](#custom-lock-store)
- [Dependencies](#dependencies)
- [Advanced Usage](#advanced-usage)
    - [Handling Lock Timeout](#handling-lock-timeout)
    - [Nested Locking](#nested-locking)
    - [Custom Lock Resource Key](#custom-lock-resource-key)
- [License](#license)

Features
--------

[](#features)

- Apply distributed locks to single entities
- Apply distributed locks to multiple entities at once
- Automatically refresh entity data from database after acquiring lock, ensuring data consistency

Installation
------------

[](#installation)

```
composer require tourze/doctrine-entity-lock-bundle
```

Add to your Symfony application's `config/bundles.php`:

```
Tourze\DoctrineEntityLockBundle\DoctrineEntityLockBundle::class => ['all' => true],
```

Usage
-----

[](#usage)

### Prerequisites

[](#prerequisites)

Ensure your entity classes implement the `Tourze\LockServiceBundle\Model\LockEntity` interface:

```
use Tourze\LockServiceBundle\Model\LockEntity;

class User implements LockEntity
{
    // ...

    public function retrieveLockResource(): string
    {
        return 'user:' . $this->id;
    }
}
```

### Locking Single Entity

[](#locking-single-entity)

```
use Tourze\DoctrineEntityLockBundle\Service\EntityLockService;

class UserService
{
    public function __construct(private readonly EntityLockService $entityLockService)
    {
    }

    public function updateUser(User $user, array $data): void
    {
        $this->entityLockService->lockEntity($user, function () use ($user, $data) {
            // Code here executes after acquiring the lock
            // Entity has been automatically refreshed to ensure data consistency
            $user->setName($data['name']);
            // ...
            return $result;
        });
    }
}
```

### Locking Multiple Entities

[](#locking-multiple-entities)

```
use Tourze\DoctrineEntityLockBundle\Service\EntityLockService;

class TransferService
{
    public function __construct(private readonly EntityLockService $entityLockService)
    {
    }

    public function transfer(Account $from, Account $to, float $amount): void
    {
        $this->entityLockService->lockEntities([$from, $to], function () use ($from, $to, $amount) {
            // Code here executes after acquiring all locks
            // All entities have been automatically refreshed to ensure data consistency
            $from->debit($amount);
            $to->credit($amount);
            // ...
            return $result;
        });
    }
}
```

Testing
-------

[](#testing)

Run tests:

```
./vendor/bin/phpunit packages/doctrine-entity-lock-bundle/tests
```

Configuration
-------------

[](#configuration)

This Bundle uses default configuration, but you can customize lock behavior through the following methods:

### Custom Lock Timeout

[](#custom-lock-timeout)

You can customize lock timeout by configuring the `LockService` in your service definitions:

```
# config/services.yaml
services:
    Tourze\LockServiceBundle\Service\LockService:
        arguments:
            $defaultTtl: 300 # Default lock time (seconds)
            $maxRetries: 3   # Maximum retry count
```

### Custom Lock Store

[](#custom-lock-store)

By default, locks use Symfony's default lock store. You can configure different storage backends:

```
# config/packages/lock.yaml
framework:
    lock:
        default: redis
        resources:
            redis:
                redis: 'redis://localhost:6379'
```

Dependencies
------------

[](#dependencies)

This Bundle depends on the following components:

- **doctrine/orm**: ^3.0
- **doctrine/doctrine-bundle**: ^2.13
- **symfony/framework-bundle**: ^7.3
- **symfony/lock**: ^7.3
- **tourze/lock-service-bundle**: Provides distributed locking base services
- **tourze/bundle-dependency**: Automatically manages Bundle dependencies

Development dependencies:

- **phpunit/phpunit**: ^11.5
- **phpstan/phpstan**: ^2.1

Advanced Usage
--------------

[](#advanced-usage)

### Handling Lock Timeout

[](#handling-lock-timeout)

When unable to acquire a lock, the service will throw an exception. You can handle this by catching the exception:

```
use Tourze\LockServiceBundle\Exception\LockAcquisitionException;

try {
    $this->entityLockService->lockEntity($user, function () use ($user) {
        // Handle business logic
    });
} catch (LockAcquisitionException $e) {
    // Handle lock conflict
    throw new \RuntimeException('User is being modified by another process, please try again later');
}
```

### Nested Locking

[](#nested-locking)

Support for nested locking of different entities:

```
$this->entityLockService->lockEntity($order, function () use ($order) {
    // Process order

    $this->entityLockService->lockEntity($order->getUser(), function () use ($order) {
        // Process user data simultaneously
    });
});
```

### Custom Lock Resource Key

[](#custom-lock-resource-key)

By implementing the `retrieveLockResource()` method of the `LockEntity` interface, you can customize the lock key:

```
class Order implements LockEntity
{
    public function retrieveLockResource(): string
    {
        // Use order number as lock key to ensure uniqueness
        return sprintf('order:%s:%s', $this->getOrderNumber(), $this->getId());
    }
}
```

License
-------

[](#license)

MIT

###  Health Score

37

—

LowBetter than 83% of packages

Maintenance74

Regular maintenance activity

Popularity14

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity40

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~82 days

Total

4

Last Release

143d ago

Major Versions

0.0.2 → 1.0.02025-11-01

### Community

Maintainers

![](https://www.gravatar.com/avatar/e354fdb316da535dfa8ba2e9193a473c403b6bc6fb9170778d1dc50e304c6e9d?d=identicon)[tourze](/maintainers/tourze)

---

Top Contributors

[![tourze](https://avatars.githubusercontent.com/u/13899502?v=4)](https://github.com/tourze "tourze (1 commits)")

---

Tags

doctrinesymfony

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/tourze-doctrine-entity-lock-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/tourze-doctrine-entity-lock-bundle/health.svg)](https://phpackages.com/packages/tourze-doctrine-entity-lock-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[easycorp/easyadmin-bundle

Admin generator for Symfony applications

4.3k16.7M310](/packages/easycorp-easyadmin-bundle)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[contao/core-bundle

Contao Open Source CMS

1231.6M2.3k](/packages/contao-core-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
