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 RedisLockEngine

Redis-based lock engine.

Uses Redis SET with NX and EX options for atomic lock acquisition. This provides a reliable distributed locking mechanism.

Supports both a single Redis node (or primary behind a proxy) and Redis Cluster via phpredis' RedisCluster client. Cluster mode is enabled by providing nodes (and optionally clusterName).

Configuration options:

  • host: Redis server hostname (default: '127.0.0.1'). Non-cluster only.
  • port: Redis server port (default: 6379). Non-cluster only.
  • password: Redis server password (default: false).
  • database: Redis database index (default: 0). Non-cluster only.
  • timeout: Connection timeout in seconds (default: 0).
  • readTimeout: Read timeout in seconds (default: 0). Cluster only.
  • persistent: Use persistent connections (default: true).
  • prefix: Prefix for lock keys (default: 'lock_').
  • ttl: Default lock TTL in seconds (default: 300).
  • nodes: List of <ip>:<port> seed nodes for Redis Cluster. Presence of this option (or clusterName) switches the engine to cluster mode.
  • clusterName: Named cluster entry configured via redis.clusters.seeds.
  • failover: Cluster failover mode (distribute, distribute_slaves, error, none). Cluster only.
  • tls: When true, enables TLS for cluster connections. Cluster only.
Namespace: Cake\Lock\Engine

Property Summary

  • $_config protected
    array<string, mixed>

    Runtime config

  • $_configInitialized protected
    bool

    Whether the config property has already been configured with defaults

  • $_defaultConfig protected
    array<string, mixed>

    Default configuration.

  • $_redis protected
    Redis|RedisCluster

    Redis connection.

Method Summary

  • _configDelete() protected

    Deletes a single config key.

  • _configRead() protected

    Reads a config key.

  • _configWrite() protected

    Writes a config key.

  • _connect() protected

    Connect to Redis server or cluster.

  • acquire() public

    Acquire a lock for the given resource.

  • acquireBlocking() public

    Acquire a lock, waiting up to $timeout seconds if necessary.

  • configShallow() public

    Merge provided config with existing config. Unlike config() which does a recursive merge for nested keys, this method does a simple merge.

  • connectRedis() protected

    Connect to a single Redis server.

  • connectRedisCluster() protected

    Connect to a Redis Cluster.

  • deleteConfig() public

    Deletes a config key.

  • ensureValidResource() protected

    Ensure the resource identifier is valid.

  • forceRelease() public

    Force release a lock without ownership verification.

  • generateToken() protected

    Generate a unique token for lock ownership.

  • getConfig() public

    Returns the config.

  • getConfigOrFail() public

    Returns the config for this specific key.

  • init() public

    Initialize the Redis lock engine.

  • isLocked() public

    Check if a resource is currently locked.

  • key() protected

    Generate the full key for a resource.

  • refresh() public

    Refresh a lock's TTL.

  • release() public

    Release a lock.

  • setConfig() public

    Sets the config.

Method Detail

_configDelete() ¶ protected

_configDelete(string $key): void

Deletes a single config key.

Parameters
string $key

Key to delete.

Returns
void
Throws
Cake\Core\Exception\CakeException
if attempting to clobber existing config

_configRead() ¶ protected

_configRead(string|null $key): $key is null ? array : mixed

Reads a config key.

Parameters
string|null $key

Key to read.

Returns
$key is null ? array : mixed

_configWrite() ¶ protected

_configWrite(array<string, mixed>|string $key, mixed $value, string|bool $merge = false): void

Writes a config key.

Parameters
array<string, mixed>|string $key

Key to write to.

mixed $value

Value to write.

string|bool $merge optional

True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.

Returns
void
Throws
Cake\Core\Exception\CakeException
if attempting to clobber existing config

_connect() ¶ protected

_connect(): bool

Connect to Redis server or cluster.

Returns
bool

True if connection was successful.

acquire() ¶ public

acquire(string $resource, int $ttl = 300): Cake\Lock\AcquiredLock|null

Acquire a lock for the given resource.

Uses Redis SET with NX (only set if not exists) and EX (expiry in seconds) for atomic lock acquisition.

Parameters
string $resource

The resource identifier to lock.

int $ttl optional

Time-to-live in seconds.

Returns
Cake\Lock\AcquiredLock|null

Returns an AcquiredLock on success, null on failure.

acquireBlocking() ¶ public

acquireBlocking(string $resource, int $ttl = 300, int $timeout = 10, int $retryInterval = 100): Cake\Lock\AcquiredLock|null

Acquire a lock, waiting up to $timeout seconds if necessary.

This is a default blocking implementation that repeatedly attempts to acquire the lock. Engines may override this with more efficient implementations.

Parameters
string $resource

The resource identifier to lock.

int $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.

Returns
Cake\Lock\AcquiredLock|null

Returns an AcquiredLock on success, null on timeout.

configShallow() ¶ public

configShallow(array<string, mixed>|string $key, mixed|null $value = null): $this

Merge provided config with existing config. Unlike config() which does a recursive merge for nested keys, this method does a simple merge.

Setting a specific value:

$this->configShallow('key', $value);

Setting a nested value:

$this->configShallow('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
array<string, mixed>|string $key

The key to set, or a complete array of configs.

mixed|null $value optional

The value to set.

Returns
$this

connectRedis() ¶ protected

connectRedis(): bool

Connect to a single Redis server.

Returns
bool

True if connection was successful.

connectRedisCluster() ¶ protected

connectRedisCluster(): bool

Connect to a Redis Cluster.

Returns
bool

True if connection was successful.

deleteConfig() ¶ public

deleteConfig(string $key): $this

Deletes a config key.

Parameters
string $key

Key to delete. It can be a dot separated string to delete nested keys.

Returns
$this

ensureValidResource() ¶ protected

ensureValidResource(string $resource): void

Ensure the resource identifier is valid.

Parameters
string $resource

The resource to validate.

Returns
void
Throws
Cake\Lock\Exception\InvalidArgumentException
If resource is invalid.

forceRelease() ¶ public

forceRelease(string $resource): bool

Force release a lock without ownership verification.

WARNING: This should only be used for administrative purposes as it bypasses owner verification and may cause race conditions.

Parameters
string $resource

The resource identifier to force release.

Returns
bool

True if the lock was released, false otherwise.

generateToken() ¶ protected

generateToken(): string

Generate a unique token for lock ownership.

Returns
string

A unique token string.

getConfig() ¶ public

getConfig(string|null $key = null, mixed $default = null): $key is null ? array : mixed

Returns the config.

Usage

Reading the whole config:

$this->getConfig();

Reading a specific value:

$this->getConfig('key');

Reading a nested value:

$this->getConfig('some.nested.key');

Reading with default value:

$this->getConfig('some-key', 'default-value');
Parameters
string|null $key optional

The key to get or null for the whole config.

mixed $default optional

The return value when the key does not exist.

Returns
$key is null ? array : mixed

Configuration data at the named key or null if the key does not exist.

getConfigOrFail() ¶ public

getConfigOrFail(string $key): mixed

Returns the config for this specific key.

The config value for this key must exist, it can never be null.

Parameters
string $key

The key to get.

Returns
mixed

Configuration data at the named key

Throws
InvalidArgumentException

init() ¶ public

init(array<string, mixed> $config = []): bool

Initialize the Redis lock engine.

Parameters
array<string, mixed> $config optional

Configuration options.

Returns
bool

True if initialization was successful.

Throws
Cake\Core\Exception\CakeException
If redis extension is not loaded.

isLocked() ¶ public

isLocked(string $resource): bool

Check if a resource is currently locked.

Note: This is a point-in-time check and the lock status may change immediately after this method returns.

Parameters
string $resource

The resource identifier to check.

Returns
bool

True if the resource is locked, false otherwise.

key() ¶ protected

key(string $resource): string

Generate the full key for a resource.

Parameters
string $resource

The resource identifier.

Returns
string

The prefixed key.

Throws
Cake\Lock\Exception\InvalidArgumentException
If resource is invalid.

refresh() ¶ public

refresh(Cake\Lock\AcquiredLock $lock, int|null $ttl = null): bool

Refresh a lock's TTL.

Uses a Lua script to atomically verify ownership and extend 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

release(Cake\Lock\AcquiredLock $lock): bool

Release a lock.

Uses a Lua script for atomic check-and-delete to ensure only the lock owner can release the lock.

Parameters
Cake\Lock\AcquiredLock $lock

The lock instance to release.

Returns
bool

True if the lock was released, false otherwise.

setConfig() ¶ public

setConfig(array<string, mixed>|string $key, mixed|null $value = null, bool $merge = true): $this

Sets the config.

Usage

Setting a specific value:

$this->setConfig('key', $value);

Setting a nested value:

$this->setConfig('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
array<string, mixed>|string $key

The key to set, or a complete array of configs.

mixed|null $value optional

The value to set.

bool $merge optional

Whether to recursively merge or overwrite existing config, defaults to true.

Returns
$this
Throws
Cake\Core\Exception\CakeException
When trying to set a key that is invalid.

Property Detail

$_config ¶ protected

Runtime config

Type
array<string, mixed>

$_configInitialized ¶ protected

Whether the config property has already been configured with defaults

Type
bool

$_defaultConfig ¶ protected

Default configuration.

  • prefix: Prefix for all lock keys. Useful for namespacing.
  • ttl: Default time-to-live in seconds for locks.
Type
array<string, mixed>

$_redis ¶ protected

Redis connection.

Type
Redis|RedisCluster
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