phpfastcache

2025-12-11 0 338

️ Please note that the V9 is mostly a PHP 8 type aware update of Phpfastcache with some significant changes !

As the V9 is relatively not compatible with previous versions, please read carefully the migration guide to ensure you the smoothest migration possible.
One of the biggest changes is the configuration system which is now an object that replace the primitive array that we used to implement back then.
Also, please note that the V9 requires at least PHP 8 or higher to works properly.


Simple Yet Powerful PHP Caching Class

More information in Wiki
The simplicity of abstraction: One class for many backend cache. You don\’t need to rewrite your code many times again.

Supported drivers at this day *

Feel free to propose a driver by making a new Pull Request, they are welcome !

Regular drivers High performances drivers Development drivers (Core) Cluster-Aggregated drivers (Core)
Apcu (Core)
(APC support removed)
Arangodb (Extension) Devnull FullReplicationCluster
Dynamodb (Extension) Cassandra
(PHP extension is no more maintained by Datastax, might be deprecated in v10)
Devrandom SemiReplicationCluster
Files (Core) CouchBasev3 (Core)
(Will be deprecated as of v10)
Memory
(Previously named Memstatic)
MasterSlaveReplicationCluster
Firestore (Extension) CouchBasev4 (Extension) RandomReplicationCluster
Leveldb (Core) Couchdb (Extension)
Memcache(d) (Core) Mongodb (Extension)
Solr (Extension) Predis (Core)
Sqlite (Core) Ravendb _(Extension)
Wincache (Core)
(Deprecated as of v9.2, will be removed as of v10)
Relay (By end of 2024)
Zend Disk Cache (Core) Redis/RedisCluster (Core)
Ssdb (Core)
Zend Memory Cache (Core)

* Driver descriptions available in DOCS/DRIVERS.md

? As of v9.2 a new Couchbase extension has been released: Couchbasev4
Also a new driver extension has been added: Ravendb. The driver will be actively developed in the feature to allow better fine-grained configuration.
This new extension is the beginning of a new era for Phpfastcache along with some others:
Many drivers has been moved from the core to their own sub-repository as a standalone extension: Arangodb, Couchdb, Dynamodb, Firestore, Mongodb, Solr.
They can be easily added through composer, ex: composer install phpfastcache/couchbasev4-extension
However Couchbasev3 will stay in the core for compatibility reasons but will be deprecated.


Because caching does not mean weaken your code

Phpfastcache has been developed over the years with 3 main goals:

  • Performance: We optimized and still optimize the code to provide you the lightest library as possible
  • Security: Because caching strategies can sometimes comes with unwanted vulnerabilities, we do our best to provide you a sage & strong library as possible
  • Portability: No matter what operating system you\’re working on, we did our best to provide you the most cross-platform code as possible

Rich Development API

Phpfastcache provides you a lot of useful APIs:

Item API (ExtendedCacheItemInterface)

Method Return Description
addTag($tagName) ExtendedCacheItemInterface Adds a tag
addTags(array $tagNames) ExtendedCacheItemInterface Adds multiple tags
append($data) ExtendedCacheItemInterface Appends data to a string or an array (push)
decrement($step = 1) ExtendedCacheItemInterface Redundant joke…
expiresAfter($ttl) ExtendedCacheItemInterface Allows you to extends the lifetime of an entry without altering its value (formerly known as touch())
expiresAt($expiration) ExtendedCacheItemInterface Sets the expiration time for this cache item (as a DateTimeInterface object)
get() mixed The getter, obviously, returns your cache object
getCreationDate() \\DatetimeInterface Gets the creation date for this cache item (as a DateTimeInterface object) *
getDataAsJsonString() string Return the data as a well-formatted json string
getEncodedKey() string Returns the final and internal item identifier (key), generally used for debug purposes
getExpirationDate() ExtendedCacheItemInterface Gets the expiration date as a Datetime object
getKey() string Returns the item identifier (key)
getLength() int Gets the data length if the data is a string, array, or objects that implement \\Countable interface.
getModificationDate() \\DatetimeInterface Gets the modification date for this cache item (as a DateTimeInterface object) *
getTags() string[] Gets the tags
hasTag(string $tagName) bool Check if the cache item contain one specific tag
hasTags(array $tagNames, int $strategy): bool bool Check if the cache item contain one or more specific tag with optional strategy (default to TAG_STRATEGY_ONE)
isTagged(): bool bool Check if the cache item has at least one tag (v9.2)
getTagsAsString($separator = \', \') string Gets the data as a string separated by $separator
getTtl() int Gets the remaining Time To Live as an integer
increment($step = 1) ExtendedCacheItemInterface To allow us to count on an integer item
isEmpty() bool Checks if the data is empty or not despite the hit/miss status.
isExpired() bool Checks if your cache entry is expired
isHit() bool Checks if your cache entry exists and is still valid, it\’s the equivalent of isset()
isNull() bool Checks if the data is null or not despite the hit/miss status.
prepend($data) ExtendedCacheItemInterface Prepends data to a string or an array (unshift)
removeTag($tagName) ExtendedCacheItemInterface Removes a tag
removeTags(array $tagNames) ExtendedCacheItemInterface Removes multiple tags
set($value) ExtendedCacheItemInterface The setter, for those who missed it, can be anything except resources or non-serializer object (ex: PDO objects, file pointers, etc).
setCreationDate($expiration) \\DatetimeInterface Sets the creation date for this cache item (as a DateTimeInterface object) *
setEventManager($evtMngr) ExtendedCacheItemInterface Sets the event manager
setExpirationDate() ExtendedCacheItemInterface Alias of expireAt() (for more code logic)
setModificationDate($expiration) \\DatetimeInterface Sets the modification date for this cache item (as a DateTimeInterface object) *
setTags(array $tags) ExtendedCacheItemInterface Sets multiple tags
* Require configuration directive \”itemDetailedDate\” to be enabled, else a \\LogicException will be thrown

ItemPool API (ExtendedCacheItemPoolInterface)

Methods (By Alphabetic Order) Return Description
appendItemsByTag($tagName, $data) bool Appends items by a tag
appendItemsByTags(array $tagNames, $data) bool Appends items by one of multiple tag names
attachItem($item) void (Re-)attaches an item to the pool
clear() bool Allows you to completely empty the cache and restart from the beginning
commit() bool Persists any deferred cache items
decrementItemsByTag($tagName, $step = 1) bool Decrements items by a tag
decrementItemsByTags(array $tagNames, $step = 1) bool Decrements items by one of multiple tag names
deleteItem($key) bool Deletes an item
deleteItems(array $keys) bool Deletes one or more items
deleteItemsByTag($tagName) bool Deletes items by a tag
deleteItemsByTags(array $tagNames, int $strategy) bool Deletes items by one of multiple tag names
detachItem($item) void Detaches an item from the pool
getConfig() ConfigurationOption Returns the configuration object
getConfigOption($optionName); mixed Returns a configuration value by its key $optionName
getDefaultConfig() ConfigurationOption Returns the default configuration object (not altered by the object instance)
getDriverName() string Returns the current driver name (without the namespace)
getEventManager() EventManagerInterface Gets the event manager
getHelp() string Provides a very basic help for a specific driver
getInstanceId() string Returns the instance ID
getItem($key) ExtendedCacheItemInterface Retrieves an item and returns an empty item if not found
getItems(array $keys) ExtendedCacheItemInterface[] Retrieves one or more item and returns an array of items. As of v9.2 an internal improvement has been made to this method.
getAllItems(string $pattern = \'\') ExtendedCacheItemInterface[] (v9.2) Retrieves all cache items with a hard limit of 9999 items. Support limited to some drivers
getItemsAsJsonString(array $keys) string Returns A json string that represents an array of items
getItemsByTag($tagName, $strategy) ExtendedCacheItemInterface[] Returns items by a tag
getItemsByTags(array $tagNames, $strategy) ExtendedCacheItemInterface[] Returns items by one of multiple tag names
getItemsByTagsAsJsonString(array $tagNames, $strategy) string Returns A json string that represents an array of items corresponding
getStats() DriverStatistic Returns the cache statistics as an object, useful for checking disk space used by the cache etc.
hasEventManager() bool Check the event manager
hasItem($key) bool Tests if an item exists
incrementItemsByTag($tagName, $step = 1, $strategy) bool Increments items by a tag
incrementItemsByTags(array $tagNames, $step = 1, $strategy) bool Increments items by one of multiple tag names
isAttached($item) bool Verify if an item is (still) attached
prependItemsByTag($tagName, $data, $strategy) bool Prepends items by a tag
prependItemsByTags(array $tagNames, $data, $strategy) bool Prepends items by one of multiple tag names
save(CacheItemInterface $item) bool Persists a cache item immediately
saveDeferred(CacheItemInterface $item) bool Sets a cache item to be persisted later
saveMultiple(...$items) bool Persists multiple cache items immediately
setEventManager(EventManagerInterface $evtMngr) ExtendedCacheItemPoolInterface Sets the event manager

? in V8: Multiple strategies ($strategy) are now supported for tagging:

  • TaggableCacheItemPoolInterface::TAG_STRATEGY_ONE allows you to get cache item(s) by at least ONE of the specified matching tag(s). Default behavior.
  • TaggableCacheItemPoolInterface::TAG_STRATEGY_ALL allows you to get cache item(s) by ALL of the specified matching tag(s) (the cache item can have additional tag(s))
  • TaggableCacheItemPoolInterface::TAG_STRATEGY_ONLY allows you to get cache item(s) by ONLY the specified matching tag(s) (the cache item cannot have additional tag(s))

It also supports multiple calls, Tagging, Setup Folder for caching. Look at our examples folders for more information.

Phpfastcache versioning API

Phpfastcache provides a class that gives you basic information about your Phpfastcache installation

  • Get the API version (Item+Pool interface) with Phpfastcache\\Api::GetVersion();
  • Get the API changelog (Item+Pool interface) Phpfastcache\\Api::getChangelog();
  • Get the Phpfastcache version with Phpfastcache\\Api::getPhpfastcacheVersion();
  • Get the Phpfastcache changelog Phpfastcache\\Api::getPhpfastcacheChangelog();

Want to keep it simple ?

? Good news, as of the V6, a Psr16 adapter is provided to keep the cache simplest using very basic getters/setters:

  • get($key, $default = null);
  • set($key, $value, $ttl = null);
  • delete($key);
  • clear();
  • getMultiple($keys, $default = null);
  • setMultiple($values, $ttl = null);
  • deleteMultiple($keys);
  • has($key);

Basic usage:

<?php

use Phpfastcache\\Helper\\Psr16Adapter;

$defaultDriver = \'Files\';
$Psr16Adapter = new Psr16Adapter($defaultDriver);

if(!$Psr16Adapter->has(\'test-key\')){
    // Setter action
    $data = \'lorem ipsum\';
    $Psr16Adapter->set(\'test-key\', \'lorem ipsum\', 300);// 5 minutes
}else{
    // Getter action
    $data = $Psr16Adapter->get(\'test-key\');
}


/**
* Do your stuff with $data
*/

Internally, the Psr16 adapter calls the Phpfastcache Api via the cache manager.


Introducing to events

As of the V6, Phpfastcache provides an event mechanism.
You can subscribe to an event by passing a Closure to an active event:

<?php

use Phpfastcache\\EventManager;

/**
* Bind the event callback
*/
EventManager::getInstance()->onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){
    $item->set(\'[HACKED BY EVENT] \' . $item->get());
});

An event callback can get unbind but you MUST provide a name to the callback previously:

<?php
use Phpfastcache\\EventManager;

/**
* Bind the event callback
*/
EventManager::getInstance()->onCacheGetItem(function(ExtendedCacheItemPoolInterface $itemPool, ExtendedCacheItemInterface $item){
    $item->set(\'[HACKED BY EVENT] \' . $item->get());
}, \'myCallbackName\');


/**
* Unbind the event callback
*/
EventManager::getInstance()->unbindEventCallback(\'onCacheGetItem\', \'myCallbackName\');

? As of the V8 you can simply subscribe to every event of Phpfastcache.

More information about the implementation and the events are available on the Wiki


Introducing new helpers

As of the V6, Phpfastcache provides some helpers to make your code easier.

  • (:warning: Removed in v8, why ?) The ActOnAll Helper to help you to act on multiple instance at once.
  • The CacheConditional Helper to help you to make the basic conditional statement more easier.
  • The Psr16 adapter

May more will come in the future, feel free to contribute !


Introducing aggregated cluster support

Check out the WIKI to learn how to implement aggregated cache clustering feature.


As Fast To Implement As Opening a Beer

? Step 1: Include phpFastCache in your project with composer:

composer require phpfastcache/phpfastcache

? Step 2: Setup your website code to implement the phpFastCache calls (with Composer)

<?php
use Phpfastcache\\CacheManager;
use Phpfastcache\\Config\\ConfigurationOption;

// Setup File Path on your config files
// Please note that as of the V6.1 the \"path\" config 
// can also be used for Unix sockets (Redis, Memcache, etc)
CacheManager::setDefaultConfig(new ConfigurationOption([
    \'path\' => \'/var/www/phpfastcache.com/dev/tmp\', // or in windows \"C:/tmp/\"
]));

// In your class, function, you can call the Cache
$InstanceCache = CacheManager::getInstance(\'files\');

/**
 * Try to get $products from Caching First
 * product_page is \"identity keyword\";
 */
$key = \"product_page\";
$CachedString = $InstanceCache->getItem($key);

$your_product_data = [
    \'First product\',
    \'Second product\',
    \'Third product\'
     /* ... */
];

if (!$CachedString->isHit()) {
    $CachedString->set($your_product_data)->expiresAfter(5);//in seconds, also accepts Datetime
	$InstanceCache->save($CachedString); // Save the cache item just like you do with doctrine and entities

    echo \'FIRST LOAD // WROTE OBJECT TO CACHE // RELOAD THE PAGE AND SEE // \';
    echo $CachedString->get();

} else {
    echo \'READ FROM CACHE // \';
    echo $CachedString->get()[0];// Will print \'First product\'
}

/**
 * use your products here or return them;
 */
echo implode(\'<br />\', $CachedString->get());// Will echo your product list

⚡ Step 3: Enjoy ! Your website is now faster than lightning !

For curious developers, there is a lot of other examples available here.

? Phpfastcache support

Found an issue or have an idea ? Come here and let us know !

下载源码

通过命令行克隆项目:

git clone https://github.com/PHPSocialNetwork/phpfastcache.git

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

申明:本文由第三方发布,内容仅代表作者观点,与本网站无关。对本文以及其中全部或者部分内容的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。本网发布或转载文章出于传递更多信息之目的,并不意味着赞同其观点或证实其描述,也不代表本网对其真实性负责。

左子网 建站资源 phpfastcache https://www.zuozi.net/34944.html

decompiler explorer
上一篇: decompiler explorer
Spina
下一篇: Spina
常见问题
  • 1、自动:拍下后,点击(下载)链接即可下载;2、手动:拍下后,联系卖家发放即可或者联系官方找开发者发货。
查看详情
  • 1、源码默认交易周期:手动发货商品为1-3天,并且用户付款金额将会进入平台担保直到交易完成或者3-7天即可发放,如遇纠纷无限期延长收款金额直至纠纷解决或者退款!;
查看详情
  • 1、描述:源码描述(含标题)与实际源码不一致的(例:货不对板); 2、演示:有演示站时,与实际源码小于95%一致的(但描述中有”不保证完全一样、有变化的可能性”类似显著声明的除外); 3、发货:不发货可无理由退款; 4、安装:免费提供安装服务的源码但卖家不履行的; 5、收费:价格虚标,额外收取其他费用的(但描述中有显著声明或双方交易前有商定的除外); 6、其他:如质量方面的硬性常规问题BUG等。 注:经核实符合上述任一,均支持退款,但卖家予以积极解决问题则除外。
查看详情
  • 1、左子会对双方交易的过程及交易商品的快照进行永久存档,以确保交易的真实、有效、安全! 2、左子无法对如“永久包更新”、“永久技术支持”等类似交易之后的商家承诺做担保,请买家自行鉴别; 3、在源码同时有网站演示与图片演示,且站演与图演不一致时,默认按图演作为纠纷评判依据(特别声明或有商定除外); 4、在没有”无任何正当退款依据”的前提下,商品写有”一旦售出,概不支持退款”等类似的声明,视为无效声明; 5、在未拍下前,双方在QQ上所商定的交易内容,亦可成为纠纷评判依据(商定与描述冲突时,商定为准); 6、因聊天记录可作为纠纷评判依据,故双方联系时,只与对方在左子上所留的QQ、手机号沟通,以防对方不承认自我承诺。 7、虽然交易产生纠纷的几率很小,但一定要保留如聊天记录、手机短信等这样的重要信息,以防产生纠纷时便于左子介入快速处理。
查看详情

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务