psr 6_ caching interface php fig
TRANSCRIPT
-
7/25/2019 PSR 6_Caching Interface PHP FIG
1/15
PHP-FIGHomeRecommendations (PSRs)MembersBylawsFAQsGet InvolvedPSR-6: Caching InterfacePSR-6: Caching Interface
Introduction
Caching isa common way to improve the performance of any project, making
caching librariesone of the most common featuresof many frameworksand
libraries. Thishasleadto a situation where many librariesroll theirown
caching libraries, with variouslevelsof functionality. These differencesare
causing developersto have to learn multiple systemswhich may ormay not
provide the functionality they need. In addition, the developersof caching
librariesthemselvesface a choice between only supporting a limitednumber
of frameworksorcreating a large numberof adapterclasses.
A common interface forcaching systemswill solve these problems. Libraryandframework developerscan count on the caching systemsworking the
way they're expecting, while the developersof caching systemswill only have
to implement a single set of interfacesratherthan a whole assortment of
adapters.
The key words"MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT",
"SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and"OPTIONAL" in
thisdocument are to be interpretedasdescribedin RFC 2119.
Goal
The goal of thisPSR isto allowdevelopersto create cache-aware libraries
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
2/15
-
7/25/2019 PSR 6_Caching Interface PHP FIG
3/15
default duration hasbeen set, the Implementing Library MUST interpret
that asa request to cache the item forever, orforaslong asthe
underlying implementation supports.
Key- A string of at least one characterthat uniquely identifiesa cached
item. Implementing librariesMUST support keysconsisting of the
characters A-Z , a-z , 0-9 , _ , and . in any orderin UTF-8encoding and
a length of up to 64 characters. Implementing librariesMAY support
additional charactersandencodingsorlongerlengths, but must support
at least that minimum. Librariesare responsible fortheirown escaping of
key stringsasappropriate, but MUST be able to return the original
unmodifiedkey string. The following charactersare reservedforfuture
extensionsandMUST NOT be supportedby implementing libraries:
{}()/\@:
Hit- A cache hit occurswhen a Calling Library requestsan Item by key
anda matching value isfoundforthat key, andthat value hasnot expired,
andthe value isnot invalidforsome otherreason. Calling Libraries
SHOULD make sure to verify isHit() on all get() calls.
Miss- A cache missisthe opposite of a cache hit. A cache missoccurs
when a Calling Library requestsan item by key andthat value not foundforthat key, orthe value wasfoundbut hasexpired, orthe value isinvalid
forsome otherreason. An expiredvalue MUST alwaysbe considereda
cache miss.
Deferred- A deferredcache save indicatesthat a cache item may not be
persistedimmediately by the pool. A Pool object MAY delay persisting a
deferredcache item in orderto take advantage of bulk-set operations
supportedby some storage engines. A Pool MUST ensure that any
deferredcache itemsare eventually persistedanddata isnot lost, and
MAY persist them before a Calling Library requeststhat they be persisted.
When a Calling Library invokesthe commit() methodall outstanding
deferreditemsMUST be persisted. An Implementing Library MAY use
whateverlogic isappropriate to determine when to persist deferred
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
4/15
items, such asan object destructor, persisting all on save(), a timeout or
max-itemscheck orany otherappropriate logic. Requestsfora cache item
that hasbeen deferredMUST return the deferredbut not-yet-persisted
item.
Data
Implementing librariesMUST support all serializable PHP data types,
including:
Strings- Characterstringsof arbitrary size in any PHP-compatible
encoding.Integers- All integersof any size supportedby PHP, up to 64-bit signed.
Floats- All signedfloating point values.
Boolean- True andFalse.
Null- The actual null value.
Arrays- Indexed, associative andmultidimensional arraysof arbitrary
depth.
Object- Any object that supportslosslessserialization and
deserialization such that $o == unserialize(serialize($o)). ObjectsMAY
leverage PHP'sSerializable interface, __sleep() or __wakeup() magic
methods, orsimilarlanguage functionality if appropriate.
All data passedinto the Implementing Library MUST be returnedexactly as
passed. That includesthe variable type. That is, it isan errorto return (string)
5if (int) 5wasthe value saved. Implementing LibrariesMAY use PHP's
serialize()/unserialize() functionsinternally but are not requiredto do so.
Compatibility with them issimply usedasa baseline foracceptable object
values.
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
5/15
If it isnot possible to return the exact savedvalue forany reason,
implementing librariesMUST respondwith a cache missratherthan
corrupteddata.
Key Concepts
Pool
The Pool representsa collection of itemsin a caching system. The pool isa
logical Repository of all itemsit contains. All cacheable itemsare retrieved
from the Pool asan Item object, andall interaction with the whole universe of
cachedobjectshappensthrough the Pool.
Items
An Item representsa single key/value pairwithin a Pool. The key isthe
primary unique identifierforan Item andMUST be immutable. The Value
MAY be changedat any time.
Errorhandling
While caching isoften an important part of application performance, it
shouldneverbe a critical part of application functionality. Thus, an errorin a
cache system SHOULD NOT result in application failure. Forthat reason
Implementing LibrariesMUST NOT throwexceptionsotherthan those defined
by the interface, andSHOULD trap any errorsorexceptionstriggeredby an
underlying data store andnot allowthem to bubble.
An Implementing Library SHOULD log such errorsorotherwise report them to
an administratorasappropriate.
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
6/15
If a Calling Library requeststhat one ormore Itemsbe deleted, orthat a pool
be cleared, it MUST NOT be consideredan errorcondition if the specifiedkey
doesnot exist. The post-condition isthe same (the key doesnot exist, orthe
pool isempty), thusthere isno errorcondition.
Interfaces
CacheItemInterface
CacheItemInterface definesan item inside a cache system. Each Item object
MUST be associatedwith a specific key, which can be set according to the
implementing system andistypically passedby the
Cache\CacheItemPoolInterface object.
The Cache\CacheItemInterface object encapsulatesthe storage andretrieval
of cache items. Each Cache\CacheItemInterface isgeneratedby a
Cache\CacheItemPoolInterface object, which isresponsible forany required
setup aswell asassociating the object with a unique Key.
Cache\CacheItemInterface objectsMUST be able to store andretrieve any
type of PHP value definedin the Data section of thisdocument.
Calling LibrariesMUST NOT instantiate Item objectsthemselves. They may
only be requestedfrom a Pool object via the getItem() method. Calling
LibrariesSHOULD NOT assume that an Item createdby one Implementing
Library iscompatible with a Pool from anotherImplementing Library.
namespace Psr\Cache;
/**
* CacheItemInterface defines an interface for interacting with objects in
*/
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
7/15
interface CacheItemInterface
{
/**
* Returns the key for the current cache item.
*
* The key is loaded by the Implementing Library, but should be availa* the higher level callers when needed.
*
* @return string
* The key string for this cache item.
*/
public function getKey();
/**
* Retrieves the value of the item from the cache associated with this
*
* The value returned must be identical to the value originally stored
*
* If isHit() returns false, this method MUST return null. Note that n
* is a legitimate cached value, so the isHit() method SHOULD be used
* differentiate between "null value was found" and "no value was foun *
* @return mixed
* The value corresponding to this cache item's key, or null if not
*/
public function get();
/**
* Confirms if the cache item lookup resulted in a cache hit.
*
* Note: This method MUST NOT have a race condition between calling is
* and calling get().
*
* @return bool
* True if the request resulted in a cache hit. False otherwise.
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
8/15
*/
public function isHit();
/**
* Sets the value represented by this cache item.
* * The $value argument may be any item that can be serialized by PHP,
* although the method of serialization is left up to the Implementing
* Library.
*
* @param mixed $value
* The serializable value to be stored.
*
* @return static
* The invoked object.
*/
public function set($value);
/**
* Sets the expiration time for this cache item.
* * @param \DateTimeInterface $expiration
* The point in time after which the item MUST be considered expired.
* If null is passed explicitly, a default value MAY be used. If non
* the value should be stored permanently or for as long as the
* implementation allows.
*
* @return static
* The called object.
*/
public function expiresAt($expiration);
/**
* Sets the expiration time for this cache item.
*
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
9/15
* @param int|\DateInterval $time
* The period of time from the present after which the item MUST be
* expired. An integer parameter is understood to be the time in sec
* expiration. If null is passed explicitly, a default value MAY be
* If none is set, the value should be stored permanently or for as
* implementation allows. *
* @return static
* The called object.
*/
public function expiresAfter($time);
}
CacheItemPoolInterface
The primary purpose of Cache\CacheItemPoolInterface isto accept a key
from the Calling Library andreturn the associatedCache\CacheItemInterface
object. It isalso the primary point of interaction with the entire cache
collection. All configuration andinitialization of the Pool isleft up to anImplementing Library.
namespace Psr\Cache;
/**
* CacheItemPoolInterface generates CacheItemInterface objects.
*/
interface CacheItemPoolInterface
{
/**
* Returns a Cache Item representing the specified key.
*
* This method must always return a CacheItemInterface object, even in
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
5 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
10/15
* a cache miss. It MUST NOT return null.
*
* @param string $key
* The key for which to return the corresponding Cache Item.
*
* @throws InvalidArgumentException * If the $key string is not a legal value a \Psr\Cache\InvalidArgum
* MUST be thrown.
*
* @return CacheItemInterface
* The corresponding Cache Item.
*/
public function getItem($key);
/**
* Returns a traversable set of cache items.
*
* @param array $keys
* An indexed array of keys of items to retrieve.
*
* @throws InvalidArgumentException * If any of the keys in $keys are not a legal value a \Psr\Cache\In
* MUST be thrown.
*
* @return array|\Traversable
* A traversable collection of Cache Items keyed by the cache keys o
* each item. A Cache item will be returned for each key, even if th
* key is not found. However, if no keys are specified then an empty
* traversable MUST be returned instead.
*/
public function getItems(array $keys = array());
/**
* Confirms if the cache contains specified cache item.
*
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
15 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
11/15
* Note: This method MAY avoid retrieving the cached value for perform
* This could result in a race condition with CacheItemInterface::get()
* such situation use CacheItemInterface::isHit() instead.
*
* @param string $key
* The key for which to check existence. *
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgum
* MUST be thrown.
*
* @return bool
* True if item exists in the cache, false otherwise.
*/
public function hasItem($key);
/**
* Deletes all items in the pool.
*
* @return bool
* True if the pool was successfully cleared. False if there was an*/
public function clear();
/**
* Removes the item from the pool.
*
* @param string $key
* The key for which to delete
*
* @throws InvalidArgumentException
* If the $key string is not a legal value a \Psr\Cache\InvalidArgum
* MUST be thrown.
*
* @return bool
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
15 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
12/15
* True if the item was successfully removed. False if there was an
*/
public function deleteItem($key);
/**
* Removes multiple items from the pool. *
* @param array $keys
* An array of keys that should be removed from the pool.
* @throws InvalidArgumentException
* If any of the keys in $keys are not a legal value a \Psr\Cache\In
* MUST be thrown.
*
* @return bool
* True if the items were successfully removed. False if there was a
*/
public function deleteItems(array $keys);
/**
* Persists a cache item immediately. *
* @param CacheItemInterface $item
* The cache item to save.
*
* @return bool
* True if the item was successfully persisted. False if there was a
*/
public function save(CacheItemInterface $item);
/**
* Sets a cache item to be persisted later.
*
* @param CacheItemInterface $item
* The cache item to save.
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
15 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
13/15
*
* @return bool
* False if the item could not be queued or if a commit was attempte
*/
public function saveDeferred(CacheItemInterface $item);
/**
* Persists any deferred cache items.
*
* @return bool
* True if all not-yet-saved items were successfully saved or there
*/
public function commit();
}
CacheException
Thisexception interface isintendedforuse when critical errorsoccur,
including but not limitedto cache setupsuch asconnecting to a cache server
orinvalidcredentialssupplied.
Any exception thrown by an Implementing Library MUST implement this
interface.
namespace Psr\Cache;
/**
* Exception interface for all exceptions thrown by an Implementing Librar
*/
interface CacheException
{
}
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
15 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
14/15
InvalidArgumentException
namespace Psr\Cache;
/**
* Exception interface for invalid cache arguments.
*
* Any time an invalid argument is passed into a method it must throw an
* exception class which implements Psr\Cache\InvalidArgumentException.
*/
interface InvalidArgumentException extends CacheException
{
}
Additional Info:
Available translations:
PSR-6: Caching Interface
PSR-6: Caching Meta Document
English (official)
Followuson Twitter Chat on IRC Channel Contribute via Github Join ourmailing list
6: Caching Interface - PHP-FIG http://www.php-fig.org/p
15 19/06/2016 0
-
7/25/2019 PSR 6_Caching Interface PHP FIG
15/15
2016PHP Framework Interop Group. Site design by Jonathan Reinink.
6: Caching Interface - PHP-FIG http://www.php-fig.org/p