CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (Github)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 5.4 Chiffon API

  • Project:
    • CakePHP
      • CakePHP
      • Authentication
      • Authorization
      • Chronos
      • Elastic Search
      • Queue
  • Version:
    • 5.4
      • 5.4
      • 5.3
      • 5.2
      • 5.1
      • 5.0
      • 4.6
      • 4.5
      • 4.4
      • 4.3
      • 4.2
      • 4.1
      • 4.0
      • 3.10
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Global
  • Cake
    • Cache
    • Collection
    • Command
    • Console
    • Container
    • Controller
    • Core
    • Database
    • Datasource
    • Error
    • Event
    • Form
    • Http
    • I18n
    • Lock
      • Engine
      • Exception
    • Log
    • Mailer
    • Network
    • ORM
    • Routing
    • TestSuite
    • Utility
    • Validation
    • View

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();
    }
}
Namespace: Cake\Lock

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
void
Throws
Cake\Lock\Exception\InvalidArgumentException
When configuration doesn't exist.
RuntimeException
If 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|null

Returns 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|null

Returns 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
bool

Success 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\LockInterface

forceRelease() ¶ 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
bool

True 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|null

Configuration 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
mixed

Configuration data at the named key.

Throws
InvalidArgumentException
If 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
bool

True 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
InvalidArgumentException
If 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
bool

True 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
bool

True 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
void
Throws
BadMethodCallException
When trying to modify an existing config.
LogicException
When 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
void

setRegistry() ¶ 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
void

synchronized() ¶ 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|null

Returns the callback result, or null if lock couldn't be acquired.

Property Detail

$_config ¶ protected static

Configuration sets.

Type
array<string|int, array<string, mixed>>

$_dsnClassMap ¶ protected static

DSN class map for lock engines.

Type
array<string, string>

$_registry ¶ protected static

Lock Registry for managing engine instances.

Type
Cake\Lock\LockRegistry<Cake\Lock\LockEngine>
OpenHub
Pingping
Linode
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (Github)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs