hammermaps-dev/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, Mongodb, Files, (P)redis, Leveldb, Memcache(d), Ssdb, Sqlite, Wincache, Xcache, Zend Data Cache.

7.0.10 2019-02-10 20:06 UTC

README

Total Downloads Latest Stable Version License Coding Standards Coding Standards
Code Climate Scrutinizer Code Quality Build Status Semver compliant Patreon

⚠️ Please note that the V7 is a major (BC breaking) update of PhpFastCache !

As the V7 is absolutely not compatible with previous versions, please read carefully the migration guide to ensure you the smoothest migration possible. One of the biggest change 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 V7 requires at least PHP7 or higher to work 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.

PHP7 Strict types enforced

As of the V7 PhpFastCache enforces the php7 strict types to make sure that it's completely php7 compatible and is type aware. This ensure you that the library is completely reliable when it come to manipulate variable types.

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

❓ Please note that as of PHP7 some php extensions were not yet updated (and will may not), we keep the code here but there's no guarantee that they are still working especially due to the cores changes introduced by Opcache.

Symfony/Drupal developers are not forgotten !

Starting with v5, phpFastCache comes with a Symfony Bundle. It is now a mature project Flex -ready, so feel free to give at try and report any bug (if any).

Also a Drupal 8 Module is currently in development, add it to your starred projects to get notified of the first public release.

Not a "Traditional" Caching

phpFastCache is not like the traditional caching methods which keep reading and writing to files, sqlite or keeping open massive amounts of connections to memcache, redis, mongodb...
Also, when you use high performances drivers, your miss hits will be drastically reduced.
Slightly different from the usual caching libraries you will find everywhere on the internet, the phpFastCache library reduces the I/O and CPU load as much as possible.

<?php
use Phpfastcache\CacheManager;

CacheManager::getInstance('files', $config);
// An alternative exists:
CacheManager::Files($config);

Reduce Database/Webservice Calls

Your website has 10,000 visitors who are online, and your dynamic page has to send 10,000 times the same queries to database or the webservice on every page load.
With phpFastCache, your page only sends 1 query to your DB/WS, and uses the cache to serve the 9,999 other visitors.
You can obviously decide the TTL that will matches your needs.

Rich Development API

PhpFastCache provides you a lot of useful APIs:

Item API (ExtendedCacheItemInterface)

* Require configuration directive "itemDetailedDate" to be enabled, else a \LogicException will be thrown

ItemPool API (ExtendedCacheItemPoolInterface)

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');

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 !

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
💾 Legacy support (Without Composer)
  • See the file examples/withoutComposer.php for more information.

⚡ 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 !