sugiphp/cache

SugiPHP缓存组件

1.1.0 2016-08-09 07:23 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:46:39 UTC


README

Build Status Scrutinizer Code Quality

SugiPHP缓存组件为APC、Memcached和基于文件的缓存系统等提供简单统一的API。

缓存系统的最重要特性之一是在指定时间后使项目失效。这将使您能够缓存一些耗时查询,例如网站上广告的总数,而不用担心某些广告被删除或发布新广告,而是设置一个时间,在此时间后该数字将失效并需要刷新。

另一个特性是,无论存储是否实际运行(缓存项目)或未运行,都不会产生任何错误或异常。相反,它将在任何get请求上返回NULL。在上面的示例中,这意味着您的代码会错误地每次都计算广告数量,可能会降低性能,但仍然可以工作。在开发或测试环境中,如果没有缓存或不需要缓存,您的代码仍然可以工作。

安装

composer require sugiphp/cache ~1.0

设置

  • 使用APC(APCu)作为缓存
<?php
use SugiPHP\Cache\Cache;
use SugiPHP\Cache\ApcStore;

$apcStore = new ApcStore();
$cache = new Cache($apcStore);

$cache->add("foo", "bar");
?>
  • 使用基于文件的缓存
<?php
use SugiPHP\Cache\Cache;
use SugiPHP\Cache\FileStore;

$cacheDir = "/path/to/tmp";
$fileStore = new FileStore($cacheDir);
$cache = new Cache($fileStore);
?>
  • 使用Memcached
<?php
use SugiPHP\Cache\Cache;
use SugiPHP\Cache\MemcachedStore;

// make a regular Memcached instance
$memcached = new Memcached();
// connect to a memcached server
$memcached->addServer("127.0.0.1", 11211);

// make a store
$mcStore = new MemcachedStore($memcached);
$cache = new Cache($mcStore);
?>
  • NullStore和ArrayStore

这两个类不是真正的缓存存储,但在开发环境和单元测试中很有用。ArrayStore只缓存脚本生命周期的值,因此未实现过期时间。脚本结束后将清除所有存储值。

<?php

use SugiPHP\Cache\Cache;
use SugiPHP\Cache\ArrayStore;

$cache = new Cache(new ArrayStore());
?>

NullStore实际上是一个假存储。它用于检查代码即使在没有缓存存储或现有存储有问题(例如,服务器上没有空间或没有与Memcached的连接)时也能正常工作。另一种用途是在您希望代码在没有缓存的情况下工作一段时间时。特别是在开发时,任何缓存机制都可能成为劣势。

<?php

use SugiPHP\Cache\Cache;
use SugiPHP\Cache\NullStore;

$cache = new Cache(new NullStore());

$cache->set("foo", "bar");
$cache->get("foo"); // will return NULL
?>

使用方法

通过在存储中设置键值对来实现缓存。

在缓存中存储一个值

<?php
$cache->set("foo", "bar");    // store a value for a maximum allowed time
$cache->set("foo", "foobar"); // store a new value with the same key
?>

如果尚未存储,则添加一个值

<?php
$cache->add("key", "foo");    // this will store a value
$cache->add("key", "foobar"); // this will fail
?>

从缓存中检索值

<?php
$cache->set("key", "value", 60); // store a value for 60 seconds
$cache->get("key"); // this will return "value" if 60 seconds are not passed and NULL after that
$cache->get("baz"); // will return NULL
?>

删除一个值

<?php
$cache->delete("key");
?>

检查值是否设置

<?php
$cache->has("key"); // will return TRUE if the "key" was set and the expiration time was not passed, and FALSE otherwise
?>

增加/减少值

<?php
$cache->set("num", 1); // store a numeric value
$cache->inc("num"); // will return 2
$cache->inc("num", 10); // will return 12
$cache->dec("num"); // will return 11
?>