PHP code example of iviphp / cache

1. Go to this page and download the library: Download iviphp/cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

iviphp / cache example snippets




declare(strict_types=1);

use Ivi\Cache\Cache;

$cache = Cache::fromConfig([
    'default' => 'array',

    'stores' => [
        'array' => [
            'driver' => 'array',
        ],
    ],
]);

$cache->set(
    'user.name',
    'Gaspard',
    300
);

$name = $cache->get('user.name');

$cache = Cache::fromConfig([
    'default' => 'file',

    'stores' => [
        'array' => [
            'driver' => 'array',
        ],

        'file' => [
            'driver' => 'file',
            'directory' => __DIR__ . '/storage/cache',
        ],
    ],
]);

$cache = Cache::fromConfig([
    'default' => [
        'driver' => 'array',
    ],
]);

$cache = Cache::fromConfig([
    'default' => 'array',

    'stores' => [
        'array' => [
            'driver' => 'array',
        ],
    ],
]);

$cache = Cache::fromConfig([
    'default' => 'file',

    'stores' => [
        'file' => [
            'driver' => 'file',
            'directory' => __DIR__ . '/storage/cache',
        ],
    ],
]);

$cache = Cache::fromConfig([
    'default' => 'file',

    'stores' => [
        'file' => [
            'driver' => 'file',

            'directory' => __DIR__ . '/storage/cache',

            'allowed_classes' => false,

            'compression_threshold' => 1024,
            'compression_level' => 6,

            'maximum_entry_bytes' => 67_108_864,

            'file_permissions' => 0600,
            'directory_permissions' => 0700,

            'create_directory' => true,
        ],
    ],
]);

$cache->set(
    'user:42',
    [
        'id' => 42,
        'name' => 'Gaspard',
    ],
    300
);

$cache->forever(
    'application.version',
    '1.0.0'
);

$cache->set(
    'application.version',
    '1.0.0',
    null
);

$user = $cache->get('user:42');

$user = $cache->get(
    'user:42',
    [
        'id' => null,
        'name' => 'Guest',
    ]
);

$cache->set(
    'optional.value',
    null,
    300
);

$cache->has('optional.value'); // true
$cache->get('optional.value'); // null

if ($cache->has('user:42')) {
    $user = $cache->get('user:42');
}

$cache->delete('user:42');

$token = $cache->pull(
    'password-reset:token',
    null
);

$cache->clear();

$cache->clearAll();

$user = $cache->remember(
    'user:42',
    300,
    function (): array {
        return [
            'id' => 42,
            'name' => 'Gaspard',
        ];
    }
);

$settings = $cache->rememberForever(
    'application.settings',
    function (): array {
        return [
            'timezone' => 'Africa/Kampala',
            'locale' => 'en',
        ];
    }
);

use DateInterval;

$cache->set(
    'report',
    $report,
    new DateInterval('PT30M')
);

$result = $cache->remember(
    'expensive.result',
    new DateInterval('PT1H'),
    function (): array {
        return performExpensiveOperation();
    }
);

$cache->set(
    'temporary.key',
    'value',
    0
);

$cache = Cache::fromConfig([
    'default' => 'file',

    'stores' => [
        'runtime' => [
            'driver' => 'array',
        ],

        'file' => [
            'driver' => 'file',
            'directory' => __DIR__ . '/storage/cache',
        ],
    ],
]);

$cache->set(
    'application.name',
    'IviPHP'
);

$runtimeCache = $cache->using('runtime');

$runtimeCache->set(
    'request.identifier',
    'request-123'
);

$cache->storeName();        // file
$runtimeCache->storeName(); // runtime

$defaultCache = $runtimeCache->usingDefault();

use Ivi\Cache\CacheManager;

$manager = new CacheManager(
    stores: [
        'array' => [
            'driver' => 'array',
        ],

        'file' => [
            'driver' => 'file',
            'directory' => __DIR__ . '/storage/cache',
        ],
    ],
    defaultStore: 'file'
);

use Ivi\Cache\Cache;

$cache = new Cache($manager);

$store = $manager->store();

$store = $manager->store('array');

$store = $manager->get('file');

$manager->register(
    'secondary',
    [
        'driver' => 'file',
        'directory' => __DIR__ . '/storage/secondary-cache',
    ]
);

use Ivi\Cache\Stores\ArrayStore;

$manager->instance(
    'local',
    new ArrayStore()
);

use Ivi\Cache\CacheInterface;
use Ivi\Cache\CacheManager;
use Ivi\Cache\Stores\ArrayStore;

$manager->register(
    'custom',
    function (
        CacheManager $manager,
        string $name
    ): CacheInterface {
        return new ArrayStore();
    }
);

$manager->replace(
    'file',
    [
        'driver' => 'file',
        'directory' => __DIR__ . '/storage/new-cache',
    ]
);

$manager->forget('file');

$manager->has('file');

$manager->isResolved('file');

$names = $manager->names();

$name = $manager->defaultName();

$manager->setDefault('array');

$manager->clearResolved();

$manager->clearAll();

$manager->flush();

use Ivi\Cache\Stores\ArrayStore;

$store = new ArrayStore();

$store->set(
    'name',
    'IviPHP',
    60
);

$name = $store->get('name');

use Ivi\Cache\Stores\FileStore;

$store = new FileStore(
    directory: __DIR__ . '/storage/cache'
);

$store->set(
    'name',
    'IviPHP',
    60
);

$count = $store->count();

$keys = $store->keys();

$removed = $store->prune();

$directory = $store->directory();

$removed = $store->prune();

$count = $store->count();

$value = $fileStore->remember(
    'expensive.operation',
    300,
    function (): mixed {
        return performExpensiveOperation();
    }
);

$fileStore = new FileStore(
    directory: __DIR__ . '/storage/cache',
    compressionThreshold: 1024,
    compressionLevel: 6
);

$fileStore = new FileStore(
    directory: __DIR__ . '/storage/cache',
    maximumEntryBytes: 67_108_864
);

'allowed_classes' => false

$cache = Cache::fromConfig([
    'default' => 'file',

    'stores' => [
        'file' => [
            'driver' => 'file',
            'directory' => __DIR__ . '/storage/cache',

            'allowed_classes' => [
                App\Data\UserData::class,
                App\Data\ReportData::class,
            ],
        ],
    ],
]);

'allowed_classes' => true

Ivi\Cache\Exceptions\CacheException

use Ivi\Cache\Exceptions\CacheException;

try {
    $cache->set(
        'user:42',
        $user,
        300
    );
} catch (CacheException $exception) {
    error_log(
        json_encode([
            'message' => $exception->getMessage(),
            'context' => $exception->context(),
        ])
    );
}

$context = $exception->context();

[
    'store' => 'file',
    'key_length' => 12,
]

use Ivi\Cache\Exceptions\CacheException;

CacheException::invalidKey(
    $key,
    $reason
);

CacheException::invalidLifetime(
    $reason
);

CacheException::storeNotFound(
    $store
);

CacheException::invalidConfiguration(
    $store,
    $reason
);

CacheException::serializationFailed(
    $key,
    $previous
);

CacheException::deserializationFailed(
    $key,
    $previous
);

CacheException::readFailed(
    $key,
    $store,
    $previous
);

CacheException::writeFailed(
    $key,
    $store,
    $previous
);

CacheException::deleteFailed(
    $key,
    $store,
    $previous
);

CacheException::clearFailed(
    $store,
    $previous
);

CacheException::directoryUnavailable(
    $directory
);

Ivi\Cache\CacheInterface

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

public function has(string $key): bool;

public function set(
    string $key,
    mixed $value,
    int|DateInterval|null $ttl = null
): bool;

public function forever(
    string $key,
    mixed $value
): bool;

public function pull(
    string $key,
    mixed $default = null
): mixed;

public function delete(string $key): bool;

public function clear(): bool;

public function remember(
    string $key,
    int|DateInterval|null $ttl,
    callable $resolver
): mixed;



declare(strict_types=1);

namespace App\Cache;

use DateInterval;
use Ivi\Cache\CacheInterface;

final class CustomStore implements CacheInterface
{
    public function get(
        string $key,
        mixed $default = null
    ): mixed {
        return $default;
    }

    public function has(string $key): bool
    {
        return false;
    }

    public function set(
        string $key,
        mixed $value,
        int|DateInterval|null $ttl = null
    ): bool {
        return true;
    }

    public function forever(
        string $key,
        mixed $value
    ): bool {
        return $this->set(
            $key,
            $value
        );
    }

    public function pull(
        string $key,
        mixed $default = null
    ): mixed {
        $value = $this->get(
            $key,
            $default
        );

        $this->delete($key);

        return $value;
    }

    public function delete(string $key): bool
    {
        return true;
    }

    public function clear(): bool
    {
        return true;
    }

    public function remember(
        string $key,
        int|DateInterval|null $ttl,
        callable $resolver
    ): mixed {
        if ($this->has($key)) {
            return $this->get($key);
        }

        $value = $resolver();

        $this->set(
            $key,
            $value,
            $ttl
        );

        return $value;
    }
}

$manager->instance(
    'custom',
    new App\Cache\CustomStore()
);



declare(strict_types=1);

use Ivi\Cache\Cache;
use Ivi\Cache\Exceptions\CacheException;

$cache = Cache::fromConfig([
    'default' => 'file',

    'stores' => [
        'runtime' => [
            'driver' => 'array',
        ],

        'file' => [
            'driver' => 'file',
            'directory' => __DIR__ . '/storage/cache',
            'compression_threshold' => 1024,
            'maximum_entry_bytes' => 67_108_864,
            'file_permissions' => 0600,
            'directory_permissions' => 0700,
        ],
    ],
]);

try {
    $user = $cache->remember(
        'users:42',
        300,
        function (): array {
            return [
                'id' => 42,
                'name' => 'Gaspard',
                'active' => true,
            ];
        }
    );

    $runtime = $cache->using('runtime');

    $runtime->set(
        'current.user',
        $user
    );

    if ($runtime->has('current.user')) {
        $currentUser = $runtime->get(
            'current.user'
        );
    }
} catch (CacheException $exception) {
    error_log(
        json_encode([
            'message' => $exception->getMessage(),
            'context' => $exception->context(),
        ])
    );

    throw $exception;
}

'allowed_classes' => false
text
src/
├── Cache.php
├── CacheInterface.php
├── CacheManager.php
├── Exceptions/
│   └── CacheException.php
└── Stores/
    ├── ArrayStore.php
    └── FileStore.php