Class Lock
Lock provides a consistent interface to distributed locking.
Configuring Lock engines
You can configure Lock engines in your application's bootstrap:
Lock::setConfig('default', [
'className' => \Cake\Lock\Engine\RedisLockEngine::class,
'host' => '127.0.0.1',
'port' => 6379,
]);
Usage examples
Prefer synchronized() when you can, as it guarantees prompt release:
$result = Lock::synchronized('my-resource', function () {
// Critical section
return $computedValue;
});
Acquiring and releasing a lock:
$lock = Lock::acquire('my-resource');
if ($lock !== null) {
try {
// Critical section
} finally {
$lock->release();
}
}
Property Summary
-
$_config protected static
array<string|int, array<string, mixed>>Configuration sets.
-
$_dsnClassMap protected static
array<string, string>DSN class map for lock engines.
-
$_registry protected static
Cake\Lock\LockRegistry<Cake\Lock\LockEngine>Lock Registry for managing engine instances.
Method Summary
-
_buildEngine() protected static
Build and get a lock engine instance.
-
acquire() public static
Acquire a lock for the given resource.
-
acquireBlocking() public static
Acquire a lock, waiting up to $timeout seconds if necessary.
-
configured() public static
Returns an array containing the named configurations
-
drop() public static
Drops a constructed adapter.
-
engine() public static
Get a lock engine instance.
-
forceRelease() public static
Force release a lock without ownership verification.
-
getConfig() public static
Reads existing configuration.
-
getConfigOrFail() public static
Reads existing configuration for a specific key.
-
getDsnClassMap() public static
Returns the DSN class map for this class.
-
getRegistry() public static
Returns the Lock Registry instance.
-
isLocked() public static
Check if a resource is currently locked.
-
parseDsn() public static
Parses a DSN into a valid connection configuration
-
refresh() public static
Refresh a lock's TTL.
-
release() public static
Release a lock.
-
setConfig() public static
This method can be used to define configuration adapters for an application.
-
setDsnClassMap() public static
Updates the DSN class map for this class.
-
setRegistry() public static
Sets the Lock Registry instance.
-
synchronized() public static
Execute a callback with an acquired lock.
Method Detail
_buildEngine() ¶ protected static
_buildEngine(string $name): void
Build and get a lock engine instance.
Parameters
-
string$name Name of the configuration.
Returns
voidThrows
Cake\Lock\Exception\InvalidArgumentExceptionWhen configuration doesn't exist.
RuntimeExceptionIf engine loading fails.
acquire() ¶ public static
acquire(string $resource, int|null $ttl = null, string $config = 'default'): Cake\Lock\AcquiredLock|null
Acquire a lock for the given resource.
Prefer synchronized() when possible. The returned lock can be released
directly and will make a best-effort attempt to release itself on destruction.
Parameters
-
string$resource The resource identifier to lock.
-
int|null$ttl optional Time-to-live in seconds. Null uses engine default.
-
string$config optional Configuration name. Defaults to 'default'.
Returns
Cake\Lock\AcquiredLock|nullReturns an AcquiredLock on success, null on failure.
acquireBlocking() ¶ public static
acquireBlocking(string $resource, int|null $ttl = null, int $timeout = 10, int $retryInterval = 100, string $config = 'default'): Cake\Lock\AcquiredLock|null
Acquire a lock, waiting up to $timeout seconds if necessary.
Parameters
-
string$resource The resource identifier to lock.
-
int|null$ttl optional Time-to-live in seconds for the lock.
-
int$timeout optional Maximum time in seconds to wait for the lock.
-
int$retryInterval optional Milliseconds to wait between retry attempts.
-
string$config optional Configuration name. Defaults to 'default'.
Returns
Cake\Lock\AcquiredLock|nullReturns an AcquiredLock on success, null on timeout.
configured() ¶ public static
configured(): array<string>
Returns an array containing the named configurations
Returns
array<string>Array of configurations.
drop() ¶ public static
drop(string $config): bool
Drops a constructed adapter.
If you wish to modify an existing configuration, you should drop it, change configuration and then re-add it.
If the implementing objects supports a $_registry object the named configuration
will also be unloaded from the registry.
Parameters
-
string$config An existing configuration you wish to remove.
Returns
boolSuccess of the removal, returns false when the config does not exist.
engine() ¶ public static
engine(string $config): Cake\Lock\LockInterface
Get a lock engine instance.
Parameters
-
string$config The name of the configured lock backend.
Returns
Cake\Lock\LockInterfaceforceRelease() ¶ public static
forceRelease(string $resource, string $config = 'default'): bool
Force release a lock without ownership verification.
Parameters
-
string$resource The resource identifier to force release.
-
string$config optional Configuration name. Defaults to 'default'.
Returns
boolTrue if the lock was released, false otherwise.
getConfig() ¶ public static
getConfig(string $key): mixed|null
Reads existing configuration.
Parameters
-
string$key The name of the configuration.
Returns
mixed|nullConfiguration data at the named key or null if the key does not exist.
getConfigOrFail() ¶ public static
getConfigOrFail(string $key): mixed
Reads existing configuration for a specific key.
The config value for this key must exist, it can never be null.
Parameters
-
string$key The name of the configuration.
Returns
mixedConfiguration data at the named key.
Throws
InvalidArgumentExceptionIf value does not exist.
getDsnClassMap() ¶ public static
getDsnClassMap(): array<string, class-string>
Returns the DSN class map for this class.
Returns
array<string, class-string>getRegistry() ¶ public static
getRegistry(): Cake\Lock\LockRegistry<Cake\Lock\LockEngine>
Returns the Lock Registry instance.
Returns
Cake\Lock\LockRegistry<Cake\Lock\LockEngine>isLocked() ¶ public static
isLocked(string $resource, string $config = 'default'): bool
Check if a resource is currently locked.
Parameters
-
string$resource The resource identifier to check.
-
string$config optional Configuration name. Defaults to 'default'.
Returns
boolTrue if the resource is locked, false otherwise.
parseDsn() ¶ public static
parseDsn(string $dsn): array<int|string, array|bool|string|null>
Parses a DSN into a valid connection configuration
This method allows setting a DSN using formatting similar to that used by PEAR::DB. The following is an example of its usage:
$dsn = 'mysql://user:pass@localhost/database?';
$config = ConnectionManager::parseDsn($dsn);
$dsn = 'Cake\Log\Engine\FileLog://?types=notice,info,debug&file=debug&path=LOGS';
$config = Log::parseDsn($dsn);
$dsn = 'smtp://user:secret@localhost:25?timeout=30&client=null&tls=null';
$config = Email::parseDsn($dsn);
$dsn = 'file:///?className=\My\Cache\Engine\FileEngine';
$config = Cache::parseDsn($dsn);
$dsn = 'File://?prefix=myapp_cake_translations_&serialize=true&duration=+2 minutes&path=/tmp/persistent/';
$config = Cache::parseDsn($dsn);
For all classes, the value of scheme is set as the value of both the className
unless they have been otherwise specified.
Note that querystring arguments are also parsed and set as values in the returned configuration.
Parameters
-
string$dsn The DSN string to convert to a configuration array
Returns
array<int|string, array|bool|string|null>The configuration array to be stored after parsing the DSN
Throws
InvalidArgumentExceptionIf not passed a string, or passed an invalid string
refresh() ¶ public static
refresh(Cake\Lock\AcquiredLock $lock, int|null $ttl = null): bool
Refresh a lock's TTL.
Parameters
-
Cake\Lock\AcquiredLock$lock The lock instance to refresh.
-
int|null$ttl optional New TTL in seconds. If null, uses the original TTL.
Returns
boolTrue if the lock was refreshed, false otherwise.
release() ¶ public static
release(Cake\Lock\AcquiredLock $lock): bool
Release a lock.
Parameters
-
Cake\Lock\AcquiredLock$lock The lock instance to release.
Returns
boolTrue if the lock was released, false otherwise.
setConfig() ¶ public static
setConfig(array<string, mixed>|string $key, mixed $config = null): void
This method can be used to define configuration adapters for an application.
To change an adapter's configuration at runtime, first drop the adapter and then reconfigure it.
Adapters will not be constructed until the first operation is done.
Usage
Assuming that the class' name is Cache the following scenarios
are supported:
Setting a cache engine up.
Cache::setConfig('default', $settings);
Injecting a constructed adapter in:
Cache::setConfig('default', $instance);
Configure multiple adapters at once:
Cache::setConfig($arrayOfConfig);
Parameters
-
array<string, mixed>|string$key The name of the configuration, or an array of multiple configs.
-
mixed$config optional Configuration value. Generally an array of name => configuration data for adapter.
Returns
voidThrows
BadMethodCallExceptionWhen trying to modify an existing config.
LogicExceptionWhen trying to store an invalid structured config array.
setDsnClassMap() ¶ public static
setDsnClassMap(array<string, class-string> $map): void
Updates the DSN class map for this class.
Parameters
-
array<string, class-string>$map Additions/edits to the class map to apply.
Returns
voidsetRegistry() ¶ public static
setRegistry(Cake\Lock\LockRegistry<Cake\Lock\LockEngine> $registry): void
Sets the Lock Registry instance.
Parameters
-
Cake\Lock\LockRegistry<Cake\Lock\LockEngine>$registry Injectable registry object.
Returns
voidsynchronized() ¶ public static
synchronized(string $resource, Closure $callback, int|null $ttl = null, int $timeout = 10, string $config = 'default'): T|null
Execute a callback with an acquired lock.
This method provides a convenient way to execute code within a lock, automatically releasing the lock when the callback completes or throws.
Templates
T
Parameters
-
string$resource The resource identifier to lock.
-
Closure$callback The callback to execute while holding the lock.
-
int|null$ttl optional Time-to-live in seconds for the lock.
-
int$timeout optional Maximum time in seconds to wait for the lock.
-
string$config optional Configuration name. Defaults to 'default'.
Returns
T|nullReturns the callback result, or null if lock couldn't be acquired.
Property Detail
$_registry ¶ protected static
Lock Registry for managing engine instances.
Type
Cake\Lock\LockRegistry<Cake\Lock\LockEngine>