PHP code example of silviooosilva / cacheer-php

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

    

silviooosilva / cacheer-php example snippets



Silviooosilva\CacheerPhp\Cacheer;

// Dependency-free, in-process. Great for tests and short CLI runs.
$cache = Cacheer::inMemory();

// Write with a TTL (seconds, "10 minutes", a DateInterval, or null = forever).
$cache->set('user:42', ['name' => 'Ada'], ttl: '10 minutes');

// Read (returns your default on a miss).
$user = $cache->get('user:42', default: null);

// On a miss, run the callback, store the result, and return it.
$report = $cache->remember('report:daily', ttl: 3600, callback: function () {
    return expensive_report();
});

// Existence and deletion.
$cache->has('user:42');     // true
$cache->delete('user:42');

$cache = Cacheer::file('/var/cache/app');      // persistent, dependency-free
$cache = Cacheer::database($pdo, 'cacheer');   // inject your own PDO
$cache = Cacheer::redis($connection);          // predis or phpredis adapter

use Silviooosilva\CacheerPhp\Stores\Support\DatabaseStoreSchema;

$pdo = new PDO('sqlite:' . __DIR__ . '/cache.sqlite');
DatabaseStoreSchema::migrate($pdo, 'cacheer');
$cache = Cacheer::database($pdo, 'cacheer');

$cache->scope('reports')->set('daily', $rows);
$cache->in('billing')->set('daily', $invoice);      // in() is an alias of scope()
$cache->scope('reports')->clear();                  // clears only that scope

// Scope applies to every operation, capabilities 

use Silviooosilva\CacheerPhp\Contracts\Cache;

function report(Cache $cache): string { /* ... */ }   // type-hint the interface

$tuned = $cache->in('reports')->withPolicy($policy);  // order does not matter
$tuned->formatted()->get('daily')->toJson();          // views compose too

use Silviooosilva\CacheerPhp\Config\CachePolicy;

$policy = CachePolicy::defaults()
    ->withTtl('10 minutes')
    ->withJitter(0.10)
    ->withNegativeTtl('30 seconds')
    ->withServeStaleOnError('2 minutes');

$cache = $cache->in('reports')->withPolicy($policy);

// Coordinate a miss through the store's lock when available.
$value = $cache->remember('key', 3600, fn () => build());

// Fresh for 30s, eligible stale data until 300s; older data recomputes synchronously.
$value = $cache->flexible('feed', fresh: 30, stale: 300, callback: fn () => build());

use Silviooosilva\CacheerPhp\Support\AfterResponseDeferredExecutor;

$executor = new AfterResponseDeferredExecutor();
$cache = new Cacheer($store, executor: $executor);

use Silviooosilva\CacheerPhp\Observability\{EventBus, MetricsCollector};
use Silviooosilva\CacheerPhp\Kernel\Ttl;

$cache = Cacheer::tiered($l1, $l2, l1MaxTtl: Ttl::seconds(10));
$cache = Cacheer::resilient($primary, $fallback);   // fall back when the breaker trips

$events = new EventBus();
$metrics = new MetricsCollector();
$events->listen($metrics->record(...));
$cache = Cacheer::instrumented($store, $events);    // value capture is off by default
$metrics->snapshot();                             // hit_rate, latency, bytes, ...

use Silviooosilva\CacheerPhp\Config\PipelineConfig;
use Silviooosilva\CacheerPhp\Storage\Encryption\Keyring;

// Load a persisted raw 32-byte key from your application's secret configuration.
$keyring = new Keyring(['current' => $encryptionKey], activeId: 'current');

$pipeline = PipelineConfig::default()
    ->withGzip()
    ->withKeyring($keyring)
    ->withMaxValueBytes(2_000_000);

$cache = Cacheer::file('/var/cache/app', $pipeline);

use Silviooosilva\CacheerPhp\Storage\Serializer\PhpSerializer;

$pipeline = $pipeline->withSerializer(new PhpSerializer(allowedClasses: false));

$cache = Cacheer::build()
    ->file('/var/cache/app')
    ->gzip()
    ->encrypt($keyring)
    ->maxValueBytes(2_000_000)
    ->defaultTtl('10 minutes')
    ->jitter(0.10)
    ->create();

use Silviooosilva\CacheerPhp\Support\CacheDataFormatter;

$json = (new CacheDataFormatter($cache->get('user:1')))->toJson();  // wrap any value
$json = $cache->formatted()->get('user:1')->toJson();               // fluent view

use Silviooosilva\CacheerPhp\Contracts\AtomicStore;

$cache->increment('visits');                  // AtomicStore
$cache->decrement('stock', 5, initial: 100);
$cache->touch('session:1', '1 hour');         // TouchStore — renew, keep value
$cache->set('product:1', ['id' => 1], ttl: 600);
$cache->tag('product:1', 'products');         // tag an already-stored key
$cache->flushTag('products');
$lock = $cache->lock('import', 30);           // LockingStore
$cache->entries();                            // InspectableStore — this scope
$cache->prune();                              // PrunableStore

// Pluggable backend? Ask first — this is honest through decorators too.
if ($cache->supports(AtomicStore::class)) { /* ... */ }

$cache->forever('config', $config);                    // no expiry, stated plainly
$cache->add('job:queued', 1, ttl: 60);                 // store only if absent
$cache->pull('flash');                                 // read once, then remove
$cache->missing('user:1');                             // inverse of has()
$cache->rememberForever('version', fn () => compute());
$cache->stats();                                       // store, scope, capabilities

use Silviooosilva\CacheerPhp\Observability\Telemetry;

Telemetry::listen(fn ($event) => $myCollector->record($event));  // opt in
// Construct the caches to observe after registering the listener.
Telemetry::reset(); // clear the global registrations for future caches

use Silviooosilva\CacheerPhp\Psr\{Psr16Cache, Psr6Pool};
use Silviooosilva\CacheerPhp\Support\SystemClock;

$psr16 = new Psr16Cache($cache);                   // Psr\SimpleCache\CacheInterface
$pool  = new Psr6Pool($cache, new SystemClock());  // Psr\Cache\CacheItemPoolInterface

$item = $pool->getItem('user42')->set(['name' => 'Ada'])->expiresAfter(600);
$pool->saveDeferred($item);
$pool->getItem('user42')->get();                  // visible before commit
$pool->commit();                                 // persist queued saves
sh
composer