0 follower

Final Class Yiisoft\Cache\Db\DbCache

InheritanceYiisoft\Cache\Db\DbCache
ImplementsPsr\SimpleCache\CacheInterface
Uses TraitsPsr\Log\LoggerAwareTrait

DbCache stores cache data in a database table.

Use {@see \Yiisoft\Cache\Db\DbSchemaManager::ensureTable()} to initialize database schema.

Public Properties

Hide inherited properties

Property Type Description Defined By
$gcProbability integer Yiisoft\Cache\Db\DbCache

Property Details

Hide inherited properties

$gcProbability public property
public integer $gcProbability 100

Method Details

Hide inherited methods

__construct() public method

public mixed __construct ( \Yiisoft\Db\Connection\ConnectionInterface $db, string $table '{{%yii_cache}}', integer $gcProbability 100 )
$db \Yiisoft\Db\Connection\ConnectionInterface

The database connection instance.

$table string

The name of the database table to store the cache data. Defaults to "cache".

$gcProbability integer

The probability (parts per million) that garbage collection (GC) should be performed when storing a piece of data in the cache. Defaults to 100, meaning 0.01% chance. This number should be between 0 and 1000000. A value 0 meaning no GC will be performed at all.

                public function __construct(
    private ConnectionInterface $db,
    private string $table = '{{%yii_cache}}',
    public int $gcProbability = 100
) {
}

            
clear() public method

public boolean clear ( )

                public function clear(): bool
{
    $this->deleteData(true);
    return true;
}

            
delete() public method

public boolean delete ( string $key )
$key string

                public function delete(string $key): bool
{
    $this->validateKey($key);
    $this->deleteData($key);
    return true;
}

            
deleteMultiple() public method

public boolean deleteMultiple ( iterable $keys )
$keys iterable

                public function deleteMultiple(iterable $keys): bool
{
    $keys = $this->iterableToArray($keys);
    $this->validateKeys($keys);
    return $this->deleteData($keys);
}

            
get() public method

public mixed get ( string $key, mixed $default null )
$key string
$default mixed

                public function get(string $key, mixed $default = null): mixed
{
    $this->validateKey($key);
    /** @var bool|float|int|string|null $value */
    $value = $this->getData($key, ['data'], 'scalar');
    return $value === false ? $default : unserialize((string) $value);
}

            
getDb() public method

Gets an instance of a database connection.

public \Yiisoft\Db\Connection\ConnectionInterface getDb ( )

                public function getDb(): ConnectionInterface
{
    return $this->db;
}

            
getMultiple() public method

public iterable getMultiple ( iterable $keys, mixed $default null )
$keys iterable
$default mixed

                public function getMultiple(iterable $keys, mixed $default = null): iterable
{
    /** @psalm-var array<array-key,array-key> $keys */
    $keys = $this->iterableToArray($keys);
    $this->validateKeys($keys);
    $values = array_fill_keys($keys, $default);
    /** @psalm-var array<string, string|resource> */
    foreach ($this->getData($keys, ['id', 'data'], 'all') as $value) {
        if (is_resource($value['data']) && get_resource_type($value['data']) === 'stream') {
            $value['data'] = stream_get_contents($value['data']);
        }
        /** @psalm-var string */
        $values[$value['id']] = unserialize((string) $value['data']);
    }
    /** @psalm-var iterable<string,mixed> */
    return $values;
}

            
getTable() public method

Gets the name of the database table to store the cache data.

public string getTable ( )

                public function getTable(): string
{
    return $this->table;
}

            
has() public method

public boolean has ( string $key )
$key string

                public function has(string $key): bool
{
    $this->validateKey($key);
    return (bool) $this->getData($key, ['id'], 'exists');
}

            
set() public method

public boolean set ( string $key, mixed $value, DateInterval|integer|string|null $ttl null )
$key string

The cache data ID.

$value mixed

The cache data value.

$ttl DateInterval|integer|string|null

The cache data TTL.

throws \Psr\SimpleCache\InvalidArgumentException

                public function set(string $key, mixed $value, DateInterval|int|string|null $ttl = null): bool
{
    $this->validateKey($key);
    $ttl = $this->normalizeTtl($ttl);
    if ($this->isExpiredTtl($ttl)) {
        return $this->delete($key);
    }
    try {
        /**
         * @psalm-suppress MixedArgumentTypeCoercion `$this->buildDataRow()` next returns `array<string, mixed>`
         */
        $this->db
            ->createCommand()
            ->upsert($this->table, $this->buildDataRow($key, $ttl, $value, true))
            ->execute();
        $this->gc();
        return true;
    } catch (Throwable $e) {
        $this->logger?->log(LogLevel::ERROR, $this->loggerMessageUpdate . $e->getMessage(), [__METHOD__]);
        return false;
    }
}

            
setLoggerMessageDelete() public method

Set logger message for delete operation failure.

public void setLoggerMessageDelete ( string $value )
$value string

The message.

                public function setLoggerMessageDelete(string $value): void
{
    $this->loggerMessageDelete = $value;
}

            
setLoggerMessageUpdate() public method

Set logger message for update operation failure.

public void setLoggerMessageUpdate ( string $value )
$value string

The message.

                public function setLoggerMessageUpdate(string $value): void
{
    $this->loggerMessageUpdate = $value;
}

            
setMultiple() public method

public boolean setMultiple ( iterable $values, DateInterval|integer|string|null $ttl null )
$values iterable

A list of key => value pairs for a multiple-set operation.

$ttl DateInterval|integer|string|null

The cache data TTL.

throws \Psr\SimpleCache\InvalidArgumentException

                public function setMultiple(iterable $values, DateInterval|int|string|null $ttl = null): bool
{
    $ttl = $this->normalizeTtl($ttl);
    $values = $this->iterableToArray($values);
    $rows = $keys = [];
    foreach ($values as $key => $value) {
        $key = (string) $key;
        $this->validateKey($key);
        $rows[] = $this->buildDataRow($key, $ttl, $value, false);
        $keys[] = $key;
    }
    try {
        $this->deleteData($keys);
        if (!empty($rows) && !$this->isExpiredTtl($ttl)) {
            $this->db
                ->createCommand()
                ->insertBatch($this->table, $rows, ['id', 'expire', 'data'])
                ->execute();
        }
        $this->gc();
        return true;
    } catch (Throwable $e) {
        $message = $e->getMessage();
        $this->logger?->log(LogLevel::ERROR, "$this->loggerMessageUpdate$message", [__METHOD__]);
        return false;
    }
}