翻译进度
6
分块数量
4
参与人数

PSR-16 缓存接口

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。

缓存库公共接口

本文档描述了一个简单也易扩展的接口,针对缓存项目和缓存驱动。

本文档中的关键字「必须」、「不得」、「要求」、「应」、「不应」、「应该」、「不应该」、「推荐」、「可能」、「可选」,使用 RFC 2119 中的描述进行解释。

最终的实现相比本提议可能会有更多功能,当然它们必须首先实现指明的接口、功能。

1. 规范

代码可乐 翻译于 2个月前

1.1 简介

使用缓存是提升项目性能的通用方法,这使得缓存功能成为许多框架和库最常见的功能之一。如果各个缓存库提供相同的使用接口,意味着库可以丢弃他们自己的缓存实现方式,然后方便的使用框架中的缓存功能,或者使用其他专门的缓存库。

PSR-6 已经解决了这个问题,但是在一些简单的用例中显得过于繁琐。这个标准为大部分情况构建更加简单的接口标准。它独立于 PSR-6,但尽可能的兼容 PSR-6。

1.2 定义

调用库,实现库,TTL,过期和 Key 都是从 PSR-6 复制而来,因为他们意义相同。

  • 调用库 - 需要使用缓存服务的库或者代码。调用库会使用实现了该标准(PSR-16)接口的缓存服务,但不必知道这些缓存服务的具体实现方式。
lockdown56 翻译于 2个月前
  • 实现库 - 实现库负责实现这个标准(PSR-16),以便为调用库提供缓存服务。实现库 必须 提供实现了 Psr\SimpleCache\CacheInterface 接口的类。实现库 必须 以整数秒(s)作为缓存有效时长(TTL)的最小粒度。

  • 有效时长(TTL)- 有效时长 (TTL) 是指一个缓存项从存储到过期的时间长度。TTL 一般用以秒为单位的整数或者 DateInterval 实例对象表示。

  • 过期(Expiration) - 过期是指一个缓存项过期的具体时间。它通过缓存项保存时指定的有效时长(TTL)计算得到。

    如果一个存储项在 1:30:00 存储,有效时长(TTL)为 300 秒,那么这个存储项会在 1:35:00 过期(Expiration)。

    实现库 可以 让一个缓存项提前过期,但缓存项一旦到了过期时间就 必须 作为已过期处理。如果调用库存储一个缓存项时没有设置过期时间或者有效时长,或者设置为了 null,实现库 可以 指定默认值。如果没有设置默认值,实现库 必须 把该缓存项设置为永不过期,或者过期时长设置为系统所支持的最大长度。

    如果有效时长(TTL)被设置为负数或者 0,该缓存项 必须 从缓存中删除使之失效。

  • Key - 用于指定缓存项唯一性的字符串,至少一个字符长度。实现库 必须 支持由 A-Za-z0-9_. 以任意顺序并使用 UTF-8 编码组成的字符串作为 Key,支持的长度需要达到 64 个字符长度。实现库 可以 支持额外的字符和字符编码,或者支持更长的字符长度,但上面所说的必须支持。实现库存储时允许根据需要对 Key 的字符进行转义处理,但 必须 能够返回未经处理过的原始 Key 字符串。以下字符作为保留字段,实现库 必须不能 使用它们:{}()/\@:

  • 缓存(Cache)- 实现了 Psr\SimpleCache\CacheInterface 接口的对象。

  • 缓存未命中(Cache Misses) - 缓存未命中时会返回 null,因此检查一个缓存项保存的值是否为 null 是不可能的。这是跟 PSR-6 主要的不同点。
lockdown56 翻译于 2个月前

1.3 Cache

Implementations MAY provide a mechanism for a user to specify a default TTL if one is not specified for a specific cache item. If no user-specified default is provided implementations MUST default to the maximum legal value allowed by the underlying implementation. If the underlying implementation does not support TTL, the user-specified TTL MUST be silently ignored.

1.4 Data

Implementing libraries MUST support all serializable PHP data types, including:

  • Strings - Character strings of arbitrary size in any PHP-compatible encoding.
  • Integers - All integers of any size supported by PHP, up to 64-bit signed.
  • Floats - All signed floating point values.
  • Boolean - True and False.
  • Null - The null value (although it will not be distinguishable from a cache miss when reading it back out).
  • Arrays - Indexed, associative and multidimensional arrays of arbitrary depth.
  • Object - Any object that supports lossless serialization and deserialization such that $o == unserialize(serialize($o)). Objects MAY leverage PHP's Serializable interface, __sleep() or __wakeup() magic methods, or similar language functionality if appropriate.

All data passed into the Implementing Library MUST be returned exactly as passed. That includes the variable type. That is, it is an error to return (string) 5 if (int) 5 was the value saved. Implementing Libraries MAY use PHP's serialize()/unserialize() functions internally but are not required to do so. Compatibility with them is simply used as a baseline for acceptable object values.

If it is not possible to return the exact saved value for any reason, implementing libraries MUST respond with a cache miss rather than corrupted data.

2. Interfaces

2.1 CacheInterface

The cache interface defines the most basic operations on a collection of cache-entries, which entails basic reading, writing and deleting individual cache items.

In addition it has methods for dealing with multiple sets of cache entries such as writing, reading or deleting multiple cache entries at a time. This is useful when you have lots of cache reads/writes to perform, and lets you perform your operations in a single call to the cache server cutting down latency times dramatically.

An instance of CacheInterface corresponds to a single collection of cache items with a single key namespace, and is equivalent to a "Pool" in PSR-6. Different CacheInterface instances MAY be backed by the same datastore, but MUST be logically independent.

<?php

namespace Psr\SimpleCache;

interface CacheInterface
{
    /**
     * Fetches a value from the cache.
     *
     * @param string $key     The unique key of this item in the cache.
     * @param mixed  $default Default value to return if the key does not exist.
     *
     * @return mixed The value of the item from the cache, or $default in case of cache miss.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function get($key, $default = null);

    /**
     * Persists data in the cache, uniquely referenced by a key with an optional expiration TTL time.
     *
     * @param string                 $key   The key of the item to store.
     * @param mixed                  $value The value of the item to store, must be serializable.
     * @param null|int|\DateInterval $ttl   Optional. The TTL value of this item. If no value is sent and
     *                                      the driver supports TTL then the library may set a default value
     *                                      for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function set($key, $value, $ttl = null);

    /**
     * Delete an item from the cache by its unique key.
     *
     * @param string $key The unique cache key of the item to delete.
     *
     * @return bool True if the item was successfully removed. False if there was an error.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function delete($key);

    /**
     * Wipes clean the entire cache's keys.
     *
     * @return bool True on success and false on failure.
     */
    public function clear();

    /**
     * Obtains multiple cache items by their unique keys.
     *
     * @param iterable $keys    A list of keys that can obtained in a single operation.
     * @param mixed    $default Default value to return for keys that do not exist.
     *
     * @return iterable A list of key => value pairs. Cache keys that do not exist or are stale will have $default as value.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $keys is neither an array nor a Traversable,
     *   or if any of the $keys are not a legal value.
     */
    public function getMultiple($keys, $default = null);

    /**
     * Persists a set of key => value pairs in the cache, with an optional TTL.
     *
     * @param iterable               $values A list of key => value pairs for a multiple-set operation.
     * @param null|int|\DateInterval $ttl    Optional. The TTL value of this item. If no value is sent and
     *                                       the driver supports TTL then the library may set a default value
     *                                       for it or let the driver take care of that.
     *
     * @return bool True on success and false on failure.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $values is neither an array nor a Traversable,
     *   or if any of the $values are not a legal value.
     */
    public function setMultiple($values, $ttl = null);

    /**
     * Deletes multiple cache items in a single operation.
     *
     * @param iterable $keys A list of string-based keys to be deleted.
     *
     * @return bool True if the items were successfully removed. False if there was an error.
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if $keys is neither an array nor a Traversable,
     *   or if any of the $keys are not a legal value.
     */
    public function deleteMultiple($keys);

    /**
     * Determines whether an item is present in the cache.
     *
     * NOTE: It is recommended that has() is only to be used for cache warming type purposes
     * and not to be used within your live applications operations for get/set, as this method
     * is subject to a race condition where your has() will return true and immediately after,
     * another script can remove it making the state of your app out of date.
     *
     * @param string $key The cache item key.
     *
     * @return bool
     *
     * @throws \Psr\SimpleCache\InvalidArgumentException
     *   MUST be thrown if the $key string is not a legal value.
     */
    public function has($key);
}

2.2 CacheException


<?php

namespace Psr\SimpleCache;

/**
 * 库抛出异常的接口,用于所有类型异常。
 */
interface CacheException
{
}

2.3 InvalidArgumentException

<?php

namespace Psr\SimpleCache;

/**
 * 无效缓存参数异常的接口。
 *
 * 当传递一个无效参数时,必须抛出一个实现了此接口的异常。
 */
interface InvalidArgumentException extends CacheException
{
}
代码可乐 翻译于 2个月前

本文章首发在 Laravel China 社区
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

参与译者:4
讨论数量: 0
发起讨论


暂无话题~