ropi/in-memory-cache

PSR-16 兼容的内存缓存库

v0.1.1 2022-03-20 20:45 UTC

This package is auto-updated.

Last update: 2024-09-15 22:22:09 UTC


README

这个基于PHP的库提供了不同的内存缓存。

要求

  • PHP ^8.0

安装

可以通过命令行界面使用 composer 安装此库。

composer require ropi/in-memory-cache

先进先出(FIFO)

<?php
$cache = new \Ropi\InMemoryCache\FifoInMemoryCache(defaultTtl: null, maxSize: 3);

$cache->set('a', 10);
$cache->set('b', 20);
$cache->set('c', 30);

var_dump($cache->get('b')); // Prints 20 
var_dump($cache->count()); // Prints 3

$cache->set('d', 40);

var_dump($cache->count()); // Still prints 3, because cache size is limited to 3 and thus first cache entry was deleted
var_dump($cache->get('a')); // Prints NULL, because 'a' was the first cache entry
var_dump($cache->get('d')); // Prints 40

固定大小

<?php
$cache = new \Ropi\InMemoryCache\FixedSizedInMemoryCache(defaultTtl: null, maxSize: 3);

$cache->set('a', 10);
$cache->set('b', 20);
$cache->set('c', 30);

var_dump($cache->get('b')); // Prints 20 
var_dump($cache->count()); // Prints 3

$cache->set('d', 40); // Throws OverflowException, because cache size is limited to 3

生存时间(TTL)

<?php
$cache = new \Ropi\InMemoryCache\InMemoryCache(defaultTtl: 2);

$cache->set('a', 10);

var_dump($cache->get('a')); // Prints 10 

sleep(3);

var_dump($cache->get('a')); // Prints NULL, because TTL expired