PHPackages                             its-mieger/mysql-shared-locks - 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. its-mieger/mysql-shared-locks

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

its-mieger/mysql-shared-locks
=============================

Shared locks using MySQL &gt;= 5.7.5

1.1.0(5y ago)0152[1 PRs](https://github.com/its-mieger/mysql-shared-locks/pulls)proprietaryPHPCI passing

Since Jul 15Pushed 3w ago1 watchersCompare

[ Source](https://github.com/its-mieger/mysql-shared-locks)[ Packagist](https://packagist.org/packages/its-mieger/mysql-shared-locks)[ RSS](/packages/its-mieger-mysql-shared-locks/feed)WikiDiscussions master Synced today

READMEChangelogDependencies (1)Versions (4)Used By (0)

MySQL shared locks
==================

[](#mysql-shared-locks)

This package implements a MySQL based shared locks for distributed applications.

Following features are provided:

- named logs without prior registration
- timeout for lock acquiring
- TTL (time to live) for locks
- Locks are independent from Database transactions

The implemented locks guarantee to be **released by end of the process** holding them (if not done explicitly before) and they also guarantee to **never block longer than their TTL**, even the process holding them hangs longer.

Implementation details
----------------------

[](#implementation-details)

- Locks are managed using a database table (MyISAM engine to ignore transactions)
- Trying to acquire a lock twice is prevented by unique index on database table
- After lock is insert in the table MySQL's `GET_LOCK`- and `RELEASE_LOCK`-functions are used to block other processes until lock becomes free again.
- The entry in the lock table is representing the lock, not the `GET_LOCK`-object. Therefore any SQL session which still holds the `GET_LOCK`-object for the current lock is terminated via `KILL`. This also informs the other process that it no longer has the lock.
- Obsolete locks (TTL exceeded) are cleared from the able on unsuccessful acquires.

Requirements
------------

[](#requirements)

- PHP &gt;= 5.6
- MySQL &gt;= 5.7.5 (before 5.7.5 only one named lock per session can be acquired)

Database setup
--------------

[](#database-setup)

Run the following SQL to create the locks table:

```
CREATE TABLE `shared_locks` (
  `name` varchar(64) NOT NULL,
  `connection_id` bigint(20) NOT NULL,
  `created` bigint(20) NOT NULL,
  `ttl` bigint(20) NOT NULL,
  `lock_acquired` tinyint(1) NOT NULL,
  UNIQUE KEY `shared_locks_ix1` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

```

Example usage
-------------

[](#example-usage)

```
// configure database connection
SharedLock::configureConnection(DB_HOST, DB_DATABASE, DB_USER, DB_PASSWORD);

// Acquire lock (timeout = 5s, TTL = 10s)
$lock = SharedLock::lock($lockName, 5, 10);

// Release
$lock->release();

```

SQL identifier quoting
----------------------

[](#sql-identifier-quoting)

By default MySQL's default identifier quotes '`' are used. However you may adapt the quoting style if using ANSI\_QUOTES quotes to '"':

```
SharedLock::setQuoteStyle(SharedLock::QUOTE_STYLE_ANSI);

```

### Being aware that a process rarely might exceed the lock TTL

[](#being-aware-that-a-process-rarely-might-exceed-the-lock-ttl)

Imagine you having a process which has acquired a lock. When this process hangs for a long time an then suddenly continues running the lock which it acquired might be taken over by another process. This case should rarely happen but nevertheless it may.

There are two strategies to handle this:

#### 1. Using same database connection for locks and application code

[](#1-using-same-database-connection-for-locks-and-application-code)

You may pass the database connection for the locks using following command:

```
SharedLock::setConnection($pdoConnection);

```

Then use transactions to only commit data if lock has not exceeded meanwhile. Eg.:

```
// start transaction
$pdoConnection->beginTransaction();

try {
	$lock = SharedLock::lock('namedLock', 5, 10);

	/*
	 * Your application code placed here
	 */

	// commit transaction
	$pdoConnection->commit();

}
catch (Exception $ex) {

	// rollback transaction
	$pdoConnection->rollBack();

	throw $ex;
}
finally {

	// release lock
	if (!empty($lock))
		$lock->release();
}

```

If the lock would have been released meanwhile the SQL session would already have been killed and therefore your transaction will fail.

#### 2. Using assertTTL

[](#2-using-assertttl)

If using the same database connection for locks and application code in combination with transactions is not an option (or you don't use the lock for synchronizing DB operations), you can use the `assertTTL` function to check if the lock is still held and if there is enough time remaining for the process to complete the operation without fearing to lose lock meanwhile:

```
try {
	$lock = SharedLock::lock('namedLock', 5, 10);

	/*
	 * Your application code placed here
	 */

	// check if still locked
	$lock->assertTTL(5);

	/*
	 * Your application code placed here
	 */
}
finally {

	// release lock
	if (!empty($lock))
		$lock->release();
}

```

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance62

Regular maintenance activity

Popularity10

Limited adoption so far

Community4

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

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

Unknown

Total

1

Last Release

2125d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/d4062a57c91cdead9169f9e84797ada75bc2df8867a632d11521dbbff9e3231a?d=identicon)[its-mieger](/maintainers/its-mieger)

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/its-mieger-mysql-shared-locks/health.svg)

```
[![Health](https://phpackages.com/badges/its-mieger-mysql-shared-locks/health.svg)](https://phpackages.com/packages/its-mieger-mysql-shared-locks)
```

###  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.0M545](/packages/mongodb-mongodb)[ramsey/uuid-doctrine

Use ramsey/uuid as a Doctrine field type.

90340.3M211](/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)
