PHPackages                             cybercog/php-db-locker - 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. cybercog/php-db-locker

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

cybercog/php-db-locker
======================

PHP application-level database locking mechanisms

798↓100%2[1 PRs](https://github.com/cybercog/php-db-locker/pulls)PHPCI passing

Since Jan 26Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/cybercog/php-db-locker)[ Packagist](https://packagist.org/packages/cybercog/php-db-locker)[ RSS](/packages/cybercog-php-db-locker/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (3)Used By (0)

PHP DB Locker
=============

[](#php-db-locker)

[![cog-php-db-locker](https://user-images.githubusercontent.com/1849174/167773585-171bef35-8e6d-461c-b1b1-ad9d2b07290a.png)](https://user-images.githubusercontent.com/1849174/167773585-171bef35-8e6d-461c-b1b1-ad9d2b07290a.png)

 [![Releases](https://camo.githubusercontent.com/a62820ce4b900bfad3e43ef47994141f9638092ed4414ef3bcc68dff0c49474c/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f6379626572636f672f7068702d64622d6c6f636b65722e7376673f7374796c653d666c61742d737175617265)](https://github.com/cybercog/php-db-locker/releases) [![License](https://camo.githubusercontent.com/3120830b0bf11ee787dbff94964f5301066865e734c029d151c6d4ef536d5ec0/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6379626572636f672f7068702d64622d6c6f636b65722e7376673f7374796c653d666c61742d737175617265)](https://github.com/cybercog/php-db-locker/blob/master/LICENSE)

Things to decide
----------------

[](#things-to-decide)

- Keep only PDO implementation, or make Doctrine/Eloquent drivers too?
- Should callback for session lock be at the end of the params (after optional ones)?

Introduction
------------

[](#introduction)

> WARNING! This library is currently under development and may not be stable. Use in your services at your own risk.

PHP application-level database locking mechanisms to implement concurrency control patterns.

Supported drivers:

- Postgres — [PostgreSQL Advisory Locks Documentation](https://www.postgresql.org/docs/current/explicit-locking.html#ADVISORY-LOCKS)

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

[](#installation)

Pull in the package through [Composer](https://getcomposer.org/).

```
composer require cybercog/php-db-locker
```

Usage
-----

[](#usage)

### Postgres

[](#postgres)

#### Transaction-level advisory lock

[](#transaction-level-advisory-lock)

```
$dbConnection = new PDO($dsn, $username, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$locker = new \Cog\DbLocker\Postgres\PostgresAdvisoryLocker();
$lockKey = \Cog\DbLocker\Postgres\PostgresLockKey::create(
    namespace: 'user',
    value: '4',
);

$dbConnection->beginTransaction();
$lock = $locker->acquireTransactionLevelLock(
    dbConnection: $dbConnection,
    key: $lockKey,
    timeoutDuration: \Cog\DbLocker\TimeoutDuration::zero(),
);
if ($lock->wasAcquired) {
    // Execute logic if lock was successful
} else {
    // Execute logic if lock acquisition has been failed
}
$dbConnection->commit();
```

#### Lock Key Creation

[](#lock-key-creation)

Create lock keys from human-readable identifiers:

```
// Auto-generated SQL comment: "[user:4]"
$lockKey = \Cog\DbLocker\Postgres\PostgresLockKey::create(
    namespace: 'user',
    value: '4',
);

// Custom SQL comment: "payment-processing[user:4]"
$lockKey = \Cog\DbLocker\Postgres\PostgresLockKey::create(
    namespace: 'user',
    value: '4',
    humanReadableValue: 'payment-processing',
);
```

Or from pre-computed int32 pairs (e.g., from external systems):

```
// Auto-generated SQL comment: "[42:100]"
$lockKey = \Cog\DbLocker\Postgres\PostgresLockKey::createFromInternalIds(
    classId: 42,
    objectId: 100,
);

// Custom SQL comment: "order:pending[42:100]"
$lockKey = \Cog\DbLocker\Postgres\PostgresLockKey::createFromInternalIds(
    classId: 42,
    objectId: 100,
    humanReadableValue: 'order:pending',
 );
```

The SQL comment appears in PostgreSQL logs for debugging and is automatically sanitized to prevent SQL injection.

#### Session-level advisory lock

[](#session-level-advisory-lock)

Callback API

```
$dbConnection = new PDO($dsn, $username, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$locker = new \Cog\DbLocker\Postgres\PostgresAdvisoryLocker();
$lockKey = \Cog\DbLocker\Postgres\PostgresLockKey::create(
    namespace: 'user',
    value: '4',
);

$payment = $locker->withinSessionLevelLock(
    dbConnection: $dbConnection,
    key: $lockKey,
    callback: function (
        \Cog\DbLocker\Postgres\LockHandle\SessionLevelLockHandle $lock,
    ): Payment { // Define a type of $payment variable, so it will be resolved by analyzers
        if ($lock->wasAcquired) {
            // Execute logic if lock was successful
        } else {
            // Execute logic if lock acquisition has been failed
        }
    },
    timeoutDuration: \Cog\DbLocker\TimeoutDuration::zero(),
);
```

Low-level API

```
$dbConnection = new PDO($dsn, $username, $password);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$locker = new \Cog\DbLocker\Postgres\PostgresAdvisoryLocker();
$lockKey = \Cog\DbLocker\Postgres\PostgresLockKey::create(
    namespace: 'user',
    value: '4',
);

try {
    $lock = $locker->acquireSessionLevelLock(
        dbConnection: $dbConnection,
        key: $lockKey,
        timeoutDuration: \Cog\DbLocker\TimeoutDuration::zero(),
    );
    if ($lock->wasAcquired) {
        // Execute logic if lock was successful
    } else {
        // Execute logic if lock acquisition has been failed
    }
} finally {
    $lock->release();
}
```

Changelog
---------

[](#changelog)

Detailed changes for each release are documented in the [CHANGELOG.md](https://github.com/cybercog/php-db-locker/blob/master/CHANGELOG.md).

License
-------

[](#license)

- `PHP DB Locker` package is open-sourced software licensed under the [MIT license](LICENSE) by [Anton Komarev](https://komarev.com).

🌟 Stargazers over time
----------------------

[](#-stargazers-over-time)

[![Stargazers over time](https://camo.githubusercontent.com/743ecf4048c6c71d15480a6393716eadc8b1d6c7ba7b29b49844a2897a68e29b/68747470733a2f2f63686172742e79687970652e6d652f6769746875622f7265706f7369746f72792d737461722f76312f3439303336323632362e737667)](https://yhype.me?utm_source=github&utm_medium=cybercog-php-db-locker&utm_content=chart-repository-star-cumulative)

About CyberCog
--------------

[](#about-cybercog)

[CyberCog](https://cybercog.su) is a Social Unity of enthusiasts. Research the best solutions in product &amp; software development is our passion.

- [Follow us on Twitter](https://twitter.com/cybercog)

[![CyberCog](https://cloud.githubusercontent.com/assets/1849174/18418932/e9edb390-7860-11e6-8a43-aa3fad524664.png)](https://cybercog.su)

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance57

Moderate activity, may be stable

Popularity20

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity15

Early-stage or recently created project

 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.

### Community

Maintainers

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

---

Top Contributors

[![antonkomarev](https://avatars.githubusercontent.com/u/1849174?v=4)](https://github.com/antonkomarev "antonkomarev (53 commits)")

---

Tags

advisory-locksconcurrencyconcurrency-controldatabasedblocklockinglocksmutexrace-condition-preventionrace-conditions

### Embed Badge

![Health badge](/badges/cybercog-php-db-locker/health.svg)

```
[![Health](https://phpackages.com/badges/cybercog-php-db-locker/health.svg)](https://phpackages.com/packages/cybercog-php-db-locker)
```

###  Alternatives

[doctrine/orm

Object-Relational-Mapper for PHP

10.2k285.3M6.2k](/packages/doctrine-orm)[jdorn/sql-formatter

a PHP SQL highlighting library

3.9k115.1M102](/packages/jdorn-sql-formatter)[illuminate/database

The Illuminate Database package.

2.8k52.4M9.3k](/packages/illuminate-database)[mongodb/mongodb

MongoDB driver library

1.6k64.0M543](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M209](/packages/ramsey-uuid-doctrine)[reliese/laravel

Reliese Components for Laravel Framework code generation.

1.7k3.4M16](/packages/reliese-laravel)

PHPackages © 2026

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