PHP code example of charcoal / cache

1. Go to this page and download the library: Download charcoal/cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

charcoal / cache example snippets


use Charcoal\Cache\CacheConfig;
use Charcoal\Cache\ServiceProvider\CacheServiceProvider;

$container->register(new CacheServiceProvider());

$container['cache/config'] = new CacheConfig([
    'prefix' => 'foobar',
    'types'  => [ 'apc', 'memcache', 'redis' ],
]);

$pool = $this->container->get('cache');

// Create a Stash pool with the Memcached driver and a custom namespace.
$pool1 = $this->container->get('cache/builder')->build('memcache', 'altcache');

// Create a custom Stash pool with the FileSystem driver and custom features.
$pool2 = $this->container->get('cache/builder')->build('file', [
    'namespace'  => 'mycache',
    'logger'     => $this->container->get('logger.custom_logger'),
    'pool_class' => \MyApp\Cache\Pool::class,
    'item_class' => \MyApp\Cache\Item::class,
]);

// Create a Stash pool with the "memory" cache driver.
$pool3 = new \Stash\Pool($container['cache/drivers']['memory']);

// Get a Stash object from the cache pool.
$item = $pool->getItem("/user/{$userId}/info");

// Get the data from it, if any happens to be there.
$userInfo = $item->get();

// Check to see if the cache missed, which could mean that it either
// didn't exist or was stale.
if ($item->isMiss()) {
    // Run the relatively expensive code.
    $userInfo = loadUserInfoFromDatabase($userId);

    // Set the new value in $item.
    $item->set($userInfo);

    // Store the expensive code so the next time it doesn't miss.
    $pool->save($item);
}

return $userInfo;

use Charcoal\Cache\Middleware\CacheMiddleware;
use Slim\App;
use Stash\Pool;

$app = new App();

// Register middleware
$app->add(new CacheMiddleware([
    'cache'   => new Pool(),
    'methods' => [ 'GET', 'HEAD' ],
]));