狼群/cache

PHP FIG PSR-16 简单缓存实现。

v1.1.1 2023-05-22 09:38 UTC

This package is auto-updated.

Last update: 2024-09-22 12:40:49 UTC


README

此仓库包含PHP FIG PSR-16 简单缓存实现。

安装

通过Composer包,您可以在Packagist上找到它,您可以使用Composer来安装它。

$ composer require vulpes/cache

默认用法

<?php declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

$predisCache = new Cache\PredisCache(
    parameters: [
        'tcp://127.0.0.1:5380?timeout=0.100',
        'tcp://127.0.0.1:5381?timeout=0.100',
        'tcp://127.0.0.1:5382?timeout=0.100',
    ],
    options: [
        'replication' => 'sentinel',
        'service' => 'master',
    ],
    defaultTtl: new DateInterval('P1D'),
    prefix: 'cache-prefix:'
);

$predisCache = new Cache\PredisCache(
    parameters: new Predis\Client('redis://default:redispw@localhost:32768'),
    defaultTtl: null,
    prefix: 'cache-prefix:'
);

$nullCache = new Cache\NullCache(
    returnOnSet: false,
    returnOnDelete: false,
    returnOnClear: false,
    returnOnHas: false
);

$sessionHandler = new Cache\SessionHandler(
    cache: $predisCache,
    ttl: intval(ini_get('session.gc_maxlifetime')),
    prefix: 'session:'
);
$sessionHandler->register();

if (php_sapi_name() === 'cli') {
    session_id('cli-session-id');
}

session_start();

if (!$predisCache->has('id') && !array_key_exists('id', $_SESSION)) {
    $predisCache->set('id', 13);
    print 'step 1: set cache value: 13' . PHP_EOL;
}
else if (!array_key_exists('id', $_SESSION)) {
    $_SESSION['id'] = $predisCache->get('id');
    print 'step 2: set session value: ' . $predisCache->get('id') . PHP_EOL;
}
else if ($predisCache->has('id')) {
    $predisCache->delete('id');
    print 'step 3: delete cache value' . PHP_EOL;
}
else {
    print 'step 4: delete session value: ' . $_SESSION['id'] . PHP_EOL;
    session_destroy();
}