PHP code example of fyennyi / async-cache-php

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

    

fyennyi / async-cache-php example snippets


use Fyennyi\AsyncCache\AsyncCacheManager;
use React\Cache\ArrayCache;

// 1. Setup Cache (using ReactPHP ArrayCache as an example)
$cache = new ArrayCache();

// 2. Create the Manager using fluent configuration
$manager = new AsyncCacheManager(
    AsyncCacheManager::configure($cache)
        ->build()
);

use Fyennyi\AsyncCache\CacheOptions;
use Fyennyi\AsyncCache\Enum\CacheStrategy;
use React\Http\Browser;

$browser = new \React\Http\Browser();

$options = new CacheOptions(
    ttl: 60,                        // Data is fresh for 60 seconds
    strategy: CacheStrategy::Strict // Default strategy
);

$promise = $manager->wrap(
    'cache_key_user_1',
    fn() => $browser->get('https://api.example.com/users/1')->then(
        fn($response) => (string)$response->getBody()
    ),
    $options
);

// Handle the result asynchronously
$promise->then(function ($data) {
    echo "User data: " . $data;
});

use Fyennyi\AsyncCache\Enum\CacheStrategy;

new CacheOptions(
    ttl: 300,                        // Time in seconds data is considered fresh
    stale_grace_period: 86400,       // Keep stale data physically in cache for 24h
    strategy: CacheStrategy::Strict, // Strict, Background, or ForceRefresh
    rate_limit_key: 'nominatim',     // Key for rate limiting (if limiter is configured)
    serve_stale_if_limited: true,    // Return stale data if rate limited
    tags: ['geo', 'kyiv'],           // Cache tags (if adapter supports them)
    compression: false,              // Enable data compression
    compression_threshold: 1024,     // Minimum size in bytes to trigger compression
    fail_safe: true,                 // Catch cache exceptions and treat as misses
    x_fetch_beta: 1.0                // Beta coefficient for X-Fetch (0 to disable)
);

$manager->increment('page_views', 1)->then(function($newValue) {
    echo "New value: " . $newValue;
});