phpfastcache/phpfastcache

PHP Abstract Cache Class - Reduce your database call using cache system. Phpfastcache handles a lot of drivers such as Apc(u), Cassandra, CouchBase, Couchdb, Dynamodb, Firestore, Mongodb, Files, (P)redis, Leveldb, Memcache(d), Ravendb, Ssdb, Sqlite, Wincache, Xcache, Zend Data Cache.

This package is auto-updated.

Last update: 2024-12-01 00:08:40 UTC


README

Total Downloads Latest Stable Version PHPSTAN Cache Interface Extended Coding Style Simple Cache Code Climate Scrutinizer Code Quality Build Status Semver compliant License Patreon

⚠️ 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 !

* 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)

ItemPool API (ExtendedCacheItemPoolInterface)

🆕 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.

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 !