New in Symfony 4.2: PDO-based lock storage

Contributed by
Jérémy Derussé
in #27456.

The Lock component was introduced in Symfony 3.4 to create and manage locks, a mechanism to provide exclusive access to a shared resource. Out of the box it supports different storages for local locks (files, semaphores) and distributed locks (Memcache, Redis). In Symfony 4.2 we've added a new PDO-based lock storage.

This makes sense because most Symfony applications already use MySQL/MariaDB or PostgreSQL for data persistence. However, this new storage doesn't rely on the built-in locking mechanisms of those databases (pg_advisory_lock_shared for PostgreSQL and GET_LOCK for MySQL/MariaDB) because they are not reliable enough. They depend on the TCP connection and require to fine-tune the database engine in order to not accept new connections after a reboot or to define a connection timeout greater than the maximum lock duration.

The new PdoStore class requires a PDO object, a Doctrine DBAL Connection object or a DSN (Data Source Name) string to configure the storage:

1
2
3
4
5
6
7
8
use Symfony\Component\Lock\Store\PdoStore;

// a PDO, a Doctrine DBAL connection or DSN for lazy connecting through PDO
$databaseConnectionOrDSN = 'mysql:host=127.0.0.1;dbname=lock';
$store = new PdoStore($databaseConnectionOrDSN, [
    'db_username' => 'myuser',
    'db_password' => 'mypassword'
]);

Then, create the table that stores the lock information. You can use the createTable() method of the PdoStore class to do that:

1
2
3
4
5
try {
    $store->createTable();
} catch (\PDOException $exception) {
    // the table could not be created for some reason
}

Now you can create and manage the PDO-based locks as explained in the docs for any other lock type.

Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

Are there any links to what settings are recommended for the DB?
Nothing special. This store uses SGDB's ACID capabilities.

Have a look to the documentation https://symfony.com/doc/master/components/lock.html#id3

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.