xinningsu / laravel-easy-cache

按需缓存服务方法结果的一种简单方法。

v1.0.0 2021-01-08 13:12 UTC

This package is auto-updated.

Last update: 2024-09-06 12:14:41 UTC


README

按需缓存服务方法结果的一种简单方法。

MIT licensed Build Status Coverage Status Scrutinizer Code Quality Code Intelligence Status Quality Gate Status Reliability Rating Security Rating Maintainability

安装

使用composer安装此包。

composer require xinningsu/laravel-easy-cache

[可选] 将此包中的config/easy-cache.php复制到laravel项目下的config/easy-cache.php中,并进行自定义配置。更多信息请查看全局配置

使用方法

在服务类中使用EasyCache特性

class News
{
    use \Sulao\EasyCache\EasyCache;

    public function getTopNews($limit = 5)
    {
        $news = [
            ['id' => 1, 'title' => 'news 1'],
            ['id' => 2, 'title' => 'news 2'],
            ['id' => 3, 'title' => 'news 3'],
            ['id' => 4, 'title' => 'news 4'],
            ['id' => 5, 'title' => 'news 5'],
        ];

        return array_slice($news, 0, $limit);
    }
}

现在服务方法的结果可以按需缓存。

$news = new News();

// without caching
$topNews = $news->getTopNews(2);

// cache it with default configuration, ttl: 3600,
// key: serialize class name, method name and parameters as cache key,
// store: laravel default cache store
// see Global Configuration below to custom default configuration.
$topNews = $news->cache()->getTopNews(2);

// or specify the ttl
$topNews = $news->cache(300)->getTopNews(2);

// specify the ttl and cache key,
// please notice that the cache key has to be specified if there is
// a closure in parameters, because closure can not be serialized.
$topNews = $news->cache(300, 'cache-key')->getTopNews(2);

// specify ttl, cache key and store,
// store is the store defined in laravel config/cache.php
$topNews = $news->cache(300, 'cache-key', 'array')->getTopNews(2);

全局配置

如果您想自定义全局配置,请将此包中的config/easy-cache.php复制到您的laravel项目下的config/easy-cache.php中。

return [
    // If the ttl parameter is not specified when calling cache method,
    // then use this one, default value is 3600.
    'ttl' => 3600,
    
    // Value can be the store defined in config/cache.php of laravel project,
    // such as memcached, redis ... If null, using laravel default cache store.
    'store' => null,

    // This prefix will be added to the front of each cache key, so it can
    // easily refresh the whole cache by changing this. default value is null.
    'prefix' => null,

    // If this specified, the caches in the page can be refreshed via query string,
    // see Refresh Page Cache below.
    'refresh_key' => null,
];

刷新页面缓存

首先需要在config/easy-cache.php中定义refresh_key,例如

    'refresh_key' => 'clear_cache',

然后在页面上添加如下查询字符串

http://localhots/?clear_cache=1

这将刷新该页面的所有缓存,请注意,只是页面的缓存,而不是存储中的所有缓存。

许可协议

MIT