PHPackages                             gaillard/mongo-lock - 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. gaillard/mongo-lock

ActiveLibrary

gaillard/mongo-lock
===================

Distributed multi-reader lock using MongoDB

v2.0.1(11y ago)32971[1 issues](https://github.com/gaillard/mongo-lock-php/issues)MITPHPPHP &gt;=5.4.0

Since Jul 29Pushed 11y ago2 watchersCompare

[ Source](https://github.com/gaillard/mongo-lock-php)[ Packagist](https://packagist.org/packages/gaillard/mongo-lock)[ RSS](/packages/gaillard-mongo-lock/feed)WikiDiscussions master Synced 4d ago

READMEChangelog (4)Dependencies (2)Versions (5)Used By (0)

mongo-lock-php
==============

[](#mongo-lock-php)

[![Build Status](https://camo.githubusercontent.com/53720a3c670fdf0fe1ec94fbaec3c51697a205e9e7bfed477a9d2cca529d6276/68747470733a2f2f7472617669732d63692e6f72672f6761696c6c6172642f6d6f6e676f2d6c6f636b2d7068702e706e67)](https://travis-ci.org/gaillard/mongo-lock-php)

Distributed multi-reader lock using MongoDB

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

[](#requirements)

Requires PHP 5.4.0 (or later).

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

[](#installation)

To add the library as a local, per-project dependency use [Composer](http://getcomposer.org)!

```
{
    "require": {
        "gaillard/mongo-lock": "~1.0"
    }
}
```

Example
-------

[](#example)

```
$writer = function($value) {
    $db = (new \MongoClient())->selectDB('locksExample');
    $data = $db->selectCollection('data');
    $locker = new Locker($db->selectCollection('locks'), 0);

    while (true) {
        $locker->writeLock('theId', 1000);

        $data->update(['_id' => 1], ['_id' => 1, 'key' => $value], ['upsert' => true]);
        $data->update(['_id' => 2], ['_id' => 2, 'key' => $value], ['upsert' => true]);
        $data->update(['_id' => 3], ['_id' => 3, 'key' => $value], ['upsert' => true]);
        $data->update(['_id' => 4], ['_id' => 4, 'key' => $value], ['upsert' => true]);

        $locker->writeUnlock('theId');
    }
};

$reader = function() {
    $db = (new \MongoClient())->selectDB('locksExample');
    $data = $db->selectCollection('data');
    $locker = new Locker($db->selectCollection('locks'), 100000);

    while (true) {
        $readerId = $locker->readLock('theId', 1000);

        foreach ($data->find()->sort(['_id' => 1]) as $doc) {
            echo "{$doc['key']} ";
        }

        echo "\n";

        $locker->readUnlock('theId', $readerId);

        usleep(100000);
    }
};

$writerOnePid = pcntl_fork();
if ($writerOnePid === 0) {
    $writer('pie');
    exit;
}

$writerTwoPid = pcntl_fork();
if ($writerTwoPid === 0) {
    $writer('cake');
    exit;
}

$readerOnePid = pcntl_fork();
if ($readerOnePid === 0) {
    $reader();
    exit;
}

$readerTwoPid = pcntl_fork();
if ($readerTwoPid === 0) {
    $reader();
    exit;
}

sleep(4);

posix_kill($writerOnePid, SIGTERM);
posix_kill($writerTwoPid, SIGTERM);
posix_kill($readerOnePid, SIGTERM);
posix_kill($readerTwoPid, SIGTERM);
```

prints something similiar too

```
pie pie pie pie
pie pie pie pie pie
pie pie pie
pie pie pie pie pie pie pie pie

cake cake cake cake cake cake cake
cake
pie pie pie pie
cake cake cake cake
pie pie pie pie
cake cake cake cake
```

You'll notice that all the pies and cakes are always seperated by a newline. That is because there are no readers with a lock during writing. That also indicates both writers not writing at the same time. Sometimes when running the example there are more or less than four printed before a newline. That is the case when the two readers have a lock at the same time.

Contributing
------------

[](#contributing)

If you would like to contribute, please use the build process for any changes and after the build passes, send a pull request on github!

```
./build.php
```

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance13

Infrequent updates — may be unmaintained

Popularity16

Limited adoption so far

Community5

Small or concentrated contributor base

Maturity61

Established project with proven stability

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 ~9 days

Total

4

Last Release

4280d ago

Major Versions

v1.0.1 → v2.0.02014-07-30

### Community

Maintainers

![](https://www.gravatar.com/avatar/9b08e5ccb3610f5099e7d82d7241203a40dab3503709e55373babb40fa7174c2?d=identicon)[gaillard](/maintainers/gaillard)

---

Tags

mongolockdistributed

###  Code Quality

TestsPHPUnit

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/gaillard-mongo-lock/health.svg)

```
[![Health](https://phpackages.com/badges/gaillard-mongo-lock/health.svg)](https://phpackages.com/packages/gaillard-mongo-lock)
```

###  Alternatives

[mongodb/laravel-mongodb

A MongoDB based Eloquent model and Query builder for Laravel

7.1k7.2M71](/packages/mongodb-laravel-mongodb)[malkusch/lock

Mutex library for exclusive code execution.

9459.6M27](/packages/malkusch-lock)[yiisoft/yii2-mongodb

MongoDB extension for the Yii framework

3312.1M45](/packages/yiisoft-yii2-mongodb)[arvenil/ninja-mutex

Simple to use mutex implementation that can use flock, memcache, memcached, mysql or redis for locking

1873.7M27](/packages/arvenil-ninja-mutex)[desarrolla2/cache

Provides an cache interface for several adapters Apc, Apcu, File, Mongo, Memcache, Memcached, Mysql, Mongo, Redis is supported.

1322.5M47](/packages/desarrolla2-cache)[mmucklo/queue-bundle

Symfony2/3/4/5 Queue Bundle (for background jobs) supporting Mongo (Doctrine ODM), Mysql (and any Doctrine ORM), RabbitMQ, Beanstalkd, Redis, and ... {write your own}

120839.8k](/packages/mmucklo-queue-bundle)

PHPackages © 2026

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