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, so this PDO-based storage doesn't require to add a new service (like Redis or Memcache) to the infrastructure/stack.
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.
What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...