0 follower

Final Class Yiisoft\Cache\File\FileCache

InheritanceYiisoft\Cache\File\FileCache
ImplementsPsr\SimpleCache\CacheInterface

FileCache implements a cache handler using files.

For each data value being cached, FileCache will store it in a separate file. The cache files are placed under \Yiisoft\Cache\File\FileCache::$cachePath. FileCache will perform garbage collection automatically to remove expired cache files.

Please refer to \Psr\SimpleCache\CacheInterface for common cache operations that are supported by FileCache.

Constants

Hide inherited constants

Constant Value Description Defined By
EXPIRATION_EXPIRED -1 Yiisoft\Cache\File\FileCache
TTL_INFINITY 31536000 Yiisoft\Cache\File\FileCache

Method Details

Hide inherited methods

__construct() public method

See also \Yiisoft\Cache\File\FileCache::$cachePath.

public __construct( string $cachePath, integer $directoryMode 0775, string $fileSuffix '.bin', integer|null $fileMode null, integer $directoryLevel 1, integer $gcProbability 10 ): mixed
$cachePath string

The directory to store cache files.

$directoryMode integer

The permission to be set for newly created directories. This value will be used by PHP chmod() function. No umask will be applied. Defaults to 0775, meaning the directory is read-writable by owner and group, but read-only for other users.

$fileSuffix string

The cache file suffix. Defaults to '.bin'.

$fileMode integer|null

The permission to be set for newly created cache files. This value will be used by PHP chmod() function. No umask will be applied. If not set, the permission will be determined by the current environment.

$directoryLevel integer

The level of subdirectories to store cache files. Defaults to 1. If the system has huge number of cache files (e.g. one million), you may use a bigger value (usually no bigger than 3). Using subdirectories is mainly to ensure the file system is not over burdened with a single directory having too many files.

$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 10, meaning 0.001% chance. This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.

throws Yiisoft\Cache\File\CacheException

If failed to create cache directory.

                public function __construct(
    private readonly string $cachePath,
    private int $directoryMode = 0775,
    private string $fileSuffix = '.bin',
    private ?int $fileMode = null,
    private int $directoryLevel = 1,
    private int $gcProbability = 10,
) {}

            
clear() public method

public clear( ): boolean

                public function clear(): bool
{
    $this->removeCacheFiles($this->cachePath, false);
    return true;
}

            
delete() public method

public delete( string $key ): boolean
$key string

                public function delete(string $key): bool
{
    $this->validateKey($key);
    $file = $this->getCacheFile($key);
    if (!is_file($file)) {
        return true;
    }
    $result = @unlink($file);
    return $this->isLastErrorSafe($result);
}

            
deleteMultiple() public method

public deleteMultiple( iterable $keys ): boolean
$keys iterable

                public function deleteMultiple(iterable $keys): bool
{
    $keys = $this->iterableToArray($keys);
    $this->validateKeys($keys);
    foreach ($keys as $key) {
        $this->delete($key);
    }
    return true;
}

            
get() public method

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

                public function get(string $key, mixed $default = null): mixed
{
    $this->validateKey($key);
    $file = $this->getCacheFile($key);
    if (!$this->existsAndNotExpired($file) || ($filePointer = @fopen($file, 'rb')) === false) {
        return $default;
    }
    flock($filePointer, LOCK_SH);
    /**
     * @var string $value We assume that we always can read content from `$filePointer` resource.
     */
    $value = stream_get_contents($filePointer);
    flock($filePointer, LOCK_UN);
    fclose($filePointer);
    return unserialize($value);
}

            
getMultiple() public method

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

                public function getMultiple(iterable $keys, mixed $default = null): iterable
{
    $keys = $this->iterableToArray($keys);
    $this->validateKeys($keys);
    $results = [];
    foreach ($keys as $key) {
        $results[$key] = $this->get($key, $default);
    }
    return $results;
}

            
has() public method

public has( string $key ): boolean
$key string

                public function has(string $key): bool
{
    $this->validateKey($key);
    return $this->existsAndNotExpired($this->getCacheFile($key));
}

            
set() public method

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

                public function set(string $key, mixed $value, int|DateInterval|null $ttl = null): bool
{
    $this->validateKey($key);
    $this->gc();
    $expiration = $this->ttlToExpiration($ttl);
    if ($expiration <= self::EXPIRATION_EXPIRED) {
        return $this->delete($key);
    }
    $file = $this->getCacheFile($key, ensureDirectory: true);
    // If ownership differs, the touch call will fail, so we try to
    // rebuild the file from scratch by deleting it first
    // https://github.com/yiisoft/yii2/pull/16120
    if (function_exists('posix_geteuid') && is_file($file) && fileowner($file) !== posix_geteuid()) {
        @unlink($file);
    }
    if (file_put_contents($file, serialize($value), LOCK_EX) === false) {
        return false;
    }
    if ($this->fileMode !== null) {
        $result = @chmod($file, $this->fileMode);
        if (!$this->isLastErrorSafe($result)) {
            return false;
        }
    }
    $result = false;
    if (@touch($file, $expiration)) {
        clearstatcache();
        $result = true;
    }
    return $this->isLastErrorSafe($result);
}

            
setMultiple() public method

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

                public function setMultiple(iterable $values, int|DateInterval|null $ttl = null): bool
{
    $values = $this->iterableToArray($values);
    $this->validateKeys(array_map(\strval(...), array_keys($values)));
    foreach ($values as $key => $value) {
        $this->set((string) $key, $value, $ttl);
    }
    return true;
}

            
withDirectoryLevel() public method
Deprecated Use $directoryLevel in the constructor instead.

public withDirectoryLevel( integer $directoryLevel ): self
$directoryLevel integer

The level of subdirectories to store cache files. Defaults to 1. If the system has huge number of cache files (e.g. one million), you may use a bigger value (usually no bigger than 3). Using subdirectories is mainly to ensure the file system is not over burdened with a single directory having too many files.

                public function withDirectoryLevel(int $directoryLevel): self
{
    $new = clone $this;
    $new->directoryLevel = $directoryLevel;
    return $new;
}

            
withDirectoryMode() public method
Deprecated Use $directoryMode in the constructor instead.

public withDirectoryMode( integer $directoryMode ): self
$directoryMode integer

The permission to be set for newly created directories. This value will be used by PHP chmod() function. No umask will be applied. Defaults to 0775, meaning the directory is read-writable by owner and group, but read-only for other users.

                public function withDirectoryMode(int $directoryMode): self
{
    $new = clone $this;
    $new->directoryMode = $directoryMode;
    return $new;
}

            
withFileMode() public method
Deprecated Use $fileMode in the constructor instead.

public withFileMode( integer $fileMode ): self
$fileMode integer

The permission to be set for newly created cache files. This value will be used by PHP chmod() function. No umask will be applied. If not set, the permission will be determined by the current environment.

                public function withFileMode(int $fileMode): self
{
    $new = clone $this;
    $new->fileMode = $fileMode;
    return $new;
}

            
withFileSuffix() public method
Deprecated Use $fileSuffix in the constructor instead.

public withFileSuffix( string $fileSuffix ): self
$fileSuffix string

The cache file suffix. Defaults to '.bin'.

                public function withFileSuffix(string $fileSuffix): self
{
    $new = clone $this;
    $new->fileSuffix = $fileSuffix;
    return $new;
}

            
withGcProbability() public method
Deprecated Use $gcProbability in the constructor instead.

public withGcProbability( integer $gcProbability ): self
$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 10, meaning 0.001% chance. This number should be between 0 and 1000000. A value 0 means no GC will be performed at all.

                public function withGcProbability(int $gcProbability): self
{
    $new = clone $this;
    $new->gcProbability = $gcProbability;
    return $new;
}