gregwar / cache
轻量级文件系统缓存系统
Requires
- php: >=5.3
README
这是一个基于文件和目录的轻量级缓存系统。
用法
步骤 1: 安装
通过 composer
{ "require": { "gregwar/cache": "1.0.*" } }
或通过克隆仓库
git clone https://github.com/Gregwar/Cache.git
或下载
步骤 2: 设置权限
您需要确保 PHP 脚本可以访问缓存目录,例如创建一个 cache
目录(确保 Web 服务器可以写入它)
mkdir cache
步骤 3: 访问缓存
要访问缓存,您可以这样做
<?php include('vendor/autoload.php'); // If using composer use Gregwar\Cache\Cache; $cache = new Cache; $cache->setCacheDirectory('cache'); // This is the default // If the cache exists, this will return it, else, the closure will be called // to create this image $data = $cache->getOrCreate('red-square.png', array(), function($filename) { $i = imagecreatetruecolor(100, 100); imagefill($i, 0, 0, 0xff0000); imagepng($i, $filename); }); header('Content-type: image/png'); echo $data;
这将渲染一个红色方块。如果缓存文件(将类似于 `cache/r/e/d/-/s/red-square.png')存在,它将被读取;否则,将调用闭包以创建缓存文件。
API
您可以使用以下方法
setCacheDirectory($directory)
: 设置缓存目录(见下文)。setActualCacheDirectory($directory)
: 设置实际缓存目录(见下文)。exists($filename, $conditions = array())
: 检查缓存中是否存在 $filename 文件,并检查条件(见下文)。check($filename, $conditions = array())
:exists
的别名。getCacheFile($filename, $actual = false, $mkdir = false)
: 获取缓存文件。如果$actual
标志为 true,将返回实际缓存文件名(见下文),如果$mkdir
标志为 true,将创建缓存文件目录树。set($filename, $contents)
: 将内容写入 $filename 缓存文件。write($filename, $contents)
:set()
的别名。get($filename, $conditions = array())
: 如果 $filename 的缓存文件存在,则返回内容;否则,返回NULL
。setPrefixSize($prefixSize)
: 设置目录的前缀大小,默认为 5。例如,对于helloworld.txt
的缓存文件,将是'h/e/l/l/o/helloworld.txt'
。setDirectoryMode($directoryMode)
: 设置创建目录时的目录模式,默认为0755
。不影响之前创建的任何目录。getOrCreate($filename, $conditions = array(), $function, $file = false)
: 这将检查 $filename 缓存文件是否存在并验证 $conditions(见下文)。如果缓存文件正常,则返回其内容。否则,将调用 $function,将其传递给目标文件,此函数可以写入参数中给出的文件或仅返回数据。然后,将返回缓存数据。如果设置$file
标志,则返回缓存文件名而不是文件数据。
注意:考虑使用散列对 $filename 缓存文件进行哈希处理,以避免特殊字符。
条件
您可以使用条件来管理缓存中的文件过期,有两种过期方式
- 使用
max-age
,以秒为单位,设置文件的最大年龄 - 使用
younger-than
,通过传递另一个文件,这将比较修改日期,如果给定文件比缓存文件新,则重新生成缓存
例如,如果您想将文件转换为大写
<?php use Gregwar\Cache\Cache; $cache = new Cache; $data = $cache->getOrCreate('uppercase.txt', array( 'younger-than' => 'original.txt' ), function() { echo "Generating file...\n"; return strtoupper(file_get_contents('original.txt')); }); echo $data;
这将创建 uppercase.txt
缓存文件,如果缓存文件不存在或如果 original.txt
文件比缓存文件新,则将 original.txt
转换为大写。
例如
php uppercase.php # Will generate the cache file
php uppercase.php # Will not generate the cache file
touch original.txt # Sets the last modification time to now
php uppercase.php # Will re-generate the cache file
缓存目录和实际缓存目录
在某些情况下,您可能需要获取缓存文件的名称。例如,如果您正在缓存图片,您可能想将其放入一个 <img>
标签中,使用一个字符串如 cache/s/o/m/e/i/someimage.png
。这可以通过将 $file
参数传递给 getOrCreate
并将其设置为 true,或者直接使用 getCacheFile
方法(见上文)来实现。
然而,用户可见的 cache
目录与您想要访问的绝对路径并不相同。为了做到这一点,您可以同时设置缓存目录和实际缓存目录。
缓存目录是用户可见的前缀(例如:cache/s/o/m/e/i/someimage.png
),而实际缓存目录是用于实际访问图片的前缀(例如:/var/www/somesite/cache/s/o/m/e/i/someimage.png
)。这样,文件将通过绝对路径访问,并且返回的缓存文件将直接可供用户的浏览器使用。
许可证
此存储库受 MIT 许可证管理,请查看 LICENCE
文件。