globalis/wp-cubi-transient-cache

0.3.0 2023-04-21 14:36 UTC

This package is auto-updated.

Last update: 2024-09-21 18:08:02 UTC


README

PHP Version Require Latest Stable Version License

基于WordPress transients的持久化缓存库

wp-cubi

特性

  • 提供使用transients的 Cache::set()Cache::get() 方法
  • 提供 Template::get() 方法,可自动缓存所需的模板部分
  • 自动缓存WordPress导航菜单
  • 在保存菜单、保存帖子或网站URL更改时按组清除缓存

安装

composer require globalis/wp-cubi-transient-cache

用法

通用缓存

在缓存中保存一个值

<?php

use Globalis\WP\Cubi\TransientCache\Cache;

$my_value = my_expensive_function();
Cache::set('my_key', $my_value, 'my_group');

从缓存中获取一个值

<?php

use Globalis\WP\Cubi\TransientCache\Cache;

$my_value_cached = Cache::get('my_key', 'my_group');

清除单个缓存条目

<?php

use Globalis\WP\Cubi\TransientCache\Cache;

Cache::clear('my_key', 'my_group');

清除多个缓存条目

<?php

use Globalis\WP\Cubi\TransientCache\Cache;

Cache::clearGroups(['my_group']);

模板缓存

从缓存中获取模板部分

<?php

use Globalis\WP\Cubi\TransientCache\Template;

Template::get('templates/my-part', ['my_arg' => 'example'], 'my_group');

当模板部分的缓存值不存在时,Template::get() 将自动加载所需的模板部分并将其缓存,因此您只需将WordPress核心函数 get_template_part() 的调用替换为 Template::get() 即可启用模板部分的缓存。

模板缓存使用通用清除方法,使用文件路径作为键(例如 Cache::clear('templates/my-part', 'my_group');)。

导航菜单缓存

导航菜单自动缓存,并预设了几个钩子,在需要时清除它们的缓存。

您始终可以使用以下方法手动清除所有菜单缓存:

<?php

use Globalis\WP\Cubi\TransientCache\Cache;

Cache::clearGroups(['menus']);

过程式风格

上述大多数方法都可以以过程式风格调用,无需任何命名空间

<?php

wp_cubi_cache_set(string $key, mixed $value, string $group = 'all');
wp_cubi_cache_get(string $key, string $group = 'all');
wp_cubi_cache_clear(string $key, string $group = 'all');
wp_cubi_cache_clear_group(string $group = 'all');
wp_cubi_cache_clear_groups(array $groups = ['all']);
wp_cubi_get_template_part_cached(string $file, array $data = [], string $group = 'all', bool $return = false);

配置

在开发或特定环境配置文件中绕过缓存

<?php

define('WP_CUBI_TRANSIENT_CACHE_BYPASS_ALL', true);

仅绕过模板部分的缓存

<?php

define('WP_CUBI_TRANSIENT_CACHE_BYPASS_TEMPLATES', true);

禁用导航菜单的自动缓存

<?php

define('WP_CUBI_TRANSIENT_CACHE_DISABLE_AUTO_CACHE_NAV_MENUS', true);

钩子

清除所有缓存

do_action('wp-cubi\transient-cache\clear');

过滤清除钩子

apply_filters('wp-cubi\transient-cache\clear-hooks', $hooks);

开发

在打开pull请求之前,请使用 ./vendor/bin/phpcs . 和/或 ./vendor/bin/phpcbf . 检查并应用项目编码标准。