PHP code example of ez-php / cache

1. Go to this page and download the library: Download ez-php/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/ */

    

ez-php / cache example snippets


$app->register(\EzPhp\Cache\CacheServiceProvider::class);

return [
    'driver'    => getenv('CACHE_DRIVER') ?: 'array', // array | file | redis | memcached | database
    'file_path' => getenv('CACHE_PATH') ?: sys_get_temp_dir() . '/ez-cache',
    'redis'     => [
        'host'     => getenv('CACHE_REDIS_HOST') ?: '127.0.0.1',
        'port'     => (int) (getenv('CACHE_REDIS_PORT') ?: 6379),
        'database' => (int) (getenv('CACHE_REDIS_DB') ?: 0),
    ],
    'memcached' => [
        'host'   => getenv('CACHE_MEMCACHED_HOST') ?: '127.0.0.1',
        'port'   => (int) (getenv('CACHE_MEMCACHED_PORT') ?: 11211),
        'weight' => (int) (getenv('CACHE_MEMCACHED_WEIGHT') ?: 0),
    ],
    'database'  => [
        'table'      => getenv('CACHE_DB_TABLE') ?: 'cache',
        'lock_table' => getenv('CACHE_DB_LOCK_TABLE') ?: 'cache_locks',
    ],
];

$cache = $app->make(\EzPhp\Cache\CacheInterface::class);

$cache->set('key', 'value', ttl: 3600);
$value  = $cache->get('key', 'default');
$cache->forget('key');
$cache->has('key');
$result = $cache->remember('key', 60, fn () => expensiveComputation());
$cache->flush();

$cache->set('rate', (string) $decimal, 3600);
$decimal = BigDecimal::of($cache->get('rate'));

$cache->increment('page-views');           // 1
$cache->increment('page-views', 5);        // 6
$cache->decrement('stock:sku-42', 2);      // creates the key at 0 if absent, then subtracts

$tagged = $cache->tags('users');
$tagged->set('profile:42', $profile, 300);
$tagged->flush(); // invalidates all keys tagged with 'users'

$lock = $cache->lock('process-payments', ttl: 30);
if ($lock->acquire()) {
    try {
        // critical section
    } finally {
        $lock->release();
    }
}

use EzPhp\Cache\StampedeProtectedCache;

$protected = new StampedeProtectedCache($cache);
$value = $protected->remember('expensive-key', 300, fn () => heavyQuery());

use EzPhp\Cache\PrefixedCache;

$tenant = new PrefixedCache($cache, 'tenant-42:');
$tenant->set('settings', [...]);            // stored as tenant-42:settings
$tenant->tags('users')->flush();            // only this tenant's tagged entries