wp-oop / transient-cache
WP transients 的 PSR-16 包装器。
Requires
- php: ^7.4 | ^8.0
- psr/simple-cache: ^1.0
Requires (Dev)
- brain/monkey: ^2.3
- johnpbloch/wordpress-core: ^5.0
- php-stubs/wordpress-stubs: 6.3
- phpunit/phpunit: ^9.0
- slevomat/coding-standard: ^6.0
- vimeo/psalm: ^5.0
This package is auto-updated.
Last update: 2024-09-13 12:10:55 UTC
README
一个完全符合PSR-16规范的 WP transients 包装器。
详细信息
在 WordPress 中缓存值的一种常见方法是使用transients。然而,这种方法存在一些问题
- 与 WordPress 的耦合。您不能突然用另一种机制替换您正在使用的缓存机制,而一切仍然正常工作。
- 没有命名空间。所有的 transients 都位于同一个命名空间中,独立消费者无法可靠地使用任意键而不会出现冲突的风险。
- 没有真正的模块化。由于上述原因,如果您的应用程序是模块化的,它不能决定为哪些内容使用哪些缓存机制,因为那已经被您的模块决定了。
- 缺少功能。例如,无法一次性清除与特定事物相关的所有值。异常也缺失,您必须依赖模糊的返回值。
这个符合标准规范的包装器解决了所有上述问题。它是一个真正的 PSR-16 缓存,使用 WordPress transients 作为存储。异常被抛出,接口得到实现,并实现了真正的负检测。只要给每个缓存池实例一个唯一的名称,每个实例在逻辑上就独立于其他实例。应用程序再次掌控一切,使用缓存的模块也可以变得平台无关。
兼容性
CachePool
和CachePoolFactory
提供最佳实践的错误处理,当出错时抛出有意义的异常。这违反了 PSR-16,但允许您知道什么失败了。SilentPool
和SilentPoolFactory
以牺牲错误处理为代价提供了 PSR-16 兼容性,隐藏异常并返回标准兼容的值。这符合 PSR-16,但以牺牲清晰度和详尽性为代价。
使用方法
/* * Set up the factory - usually in a service definition */ use wpdb; use Psr\SimpleCache\CacheInterface; use WpOop\TransientCache\CachePoolFactory; use WpOop\TransientCache\SilentPoolFactory; /* @var $wpdb wpdb */ $factory = new CachePoolFactory($wpdb); // Optionally hide exceptions for PSR-16 compatibility $factory = new SilentPoolFactory($factory); // Optional, and not recommended for testing environments! /* * Create cache pools - usually somewhere else */ // Same wpdb instance used, default value generated automatically $pool1 = $factory->createCachePool('client-access-tokens'); $pool2 = $factory->createCachePool('remote-api-responses'); $pool3 = $factory->createCachePool('other-stuff'); /* * Use cache pools - usually injected into a client class */ // No collision of key between different pools $pool1->set('123', $someToken); $pool2->set('123', $someResponseBody); $pool3->set('123', false); // Depend on an interop standard (function (CacheInterface $cache) { // False negative detection: correctly determines that the value is actually `false` $cache->has('123'); // true $cache->get('123', uniqid('default')) === false; // true })($pool3); // Clear all values within a pool $pool2->clear(); $pool2->has('123'); // false $pool1->has('123'); // true
限制
键长度
由于底层后端(通过选项的 WordPress transients)的工作方式,池名称和缓存键的合并长度绝对不能超过 171 个字符的限制。这是因为(至少在 WP 5.0+)options 表的 option_name
字段的长度是 191 个字符,而 transients 需要使用选项名称的最长前缀 _transient_timeout_
,这加上 1 个字符的分隔符是 20 个字符。使用超过这个长度的任何内容都可能导致在Trac #15058中描述的潜在破坏性行为。
无论如何,一般建议是,消费者不应使用超过 64 个字符的缓存键,因为这是 PSR-16 规范所要求的最低长度。使用超过这个长度的任何内容都会使消费者依赖于实现细节,这会破坏互操作性。因此,缓存池名称不应超过 107 个字符。
值长度
存储后端(WP选项)声明相应的字段类型为LONGTEXT
,这允许
最多存储高达4 GB(232)的数据。因此,这是缓存值的上限。