PHP code example of andydefer / jsonl-cache

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

    

andydefer / jsonl-cache example snippets


// config/jsonl-cache.php

return [
    // Chemin de base pour les fichiers de cache
    'base_path' => env('JSONL_CACHE_PATH', storage_path('jsonl-cache')),

    // TTL par défaut en secondes (null = pas d'expiration)
    'default_ttl' => (int) env('JSONL_CACHE_TTL', 3600),

    // Nombre de niveaux de hash (1-4)
    'hash_levels' => (int) env('JSONL_CACHE_HASH_LEVELS', 2),

    // Activation/désactivation du cache
    'enabled' => (bool) env('JSONL_CACHE_ENABLED', true),

    // Préfixe ajouté aux clés
    'prefix' => env('JSONL_CACHE_PREFIX', 'cache'),
];

use AndyDefer\JsonlCache\Services\JsonlCacheService;
use AndyDefer\JsonlCache\Config\JsonlCacheConfig;
use AndyDefer\LaravelJsonl\JsonlService;
use AndyDefer\LaravelJsonl\Contexts\JsonlContext;
use AndyDefer\JsonlCache\Strategies\CachePathStrategy;
use AndyDefer\DomainStructures\Services\HydrationService;
use AndyDefer\PhpServices\Services\FileSystemService;

$config = new JsonlCacheConfig(app('config'));
$strategy = new CachePathStrategy('/tmp/cache', 2);
$fs = new FileSystemService();
$hydration = new HydrationService();
$jsonl = new JsonlService($strategy, $fs, new JsonlContext());

$cache = new JsonlCacheService($jsonl, $strategy, $config, $hydration, $fs);

use AndyDefer\JsonlCache\Contracts\JsonlCacheInterface;

class MyController extends Controller
{
    public function __construct(
        private readonly JsonlCacheInterface $cache,
    ) {}

    public function index()
    {
        // Utilisation directe
    }
}

// Stocker avec TTL par défaut (config)
$cache->set('user_123', ['name' => 'John Doe']);

// Stocker pour 1 heure
$cache->set('user_123', $userData, 3600);

// Stocker sans expiration
$cache->set('config_app', $config, null);

// Lecture simple
$user = $cache->get('user_123');

// Avec valeur par défaut
$user = $cache->get('user_123', ['name' => 'Guest']);

// Vérifier l'existence
if ($cache->has('user_123')) {
    echo "Cache hit!";
}

// Supprimer une entrée
$cache->delete('user_123');

// Vider tout le cache
$cache->clear();

// Tableau
$cache->set('array_key', ['a' => 1, 'b' => 2]);

// Objet (devient tableau)
$cache->set('object_key', (object) ['name' => 'John']);

// Scalaires
$cache->set('string_key', 'hello');
$cache->set('int_key', 42);
$cache->set('float_key', 3.14);
$cache->set('bool_key', true);
$cache->set('null_key', null);

// Lecture multiple
$values = $cache->getMultiple(['user_123', 'user_456', 'user_789'], 'default');

// Stockage multiple
$cache->setMultiple([
    'user_123' => ['name' => 'John'],
    'user_456' => ['name' => 'Jane'],
    'user_789' => ['name' => 'Bob'],
], 3600);

// Suppression multiple
$cache->deleteMultiple(['user_123', 'user_456']);

// Récupérer l'enregistrement complet
$record = $cache->getRecord('user_123');
if ($record) {
    echo $record->key;         // 'cache_user_123'
    echo $record->value;       // '{"name":"John"}'
    echo $record->expires_at;  // DateTimeVO
    echo $record->created_at;  // DateTimeVO
}

// Récupérer le JSON brut
$raw = $cache->getRaw('user_123');
// '{"key":"cache_user_123","value":"{\"name\":\"John\"}","expires_at":"..."}'

$cache->set('key', 'old value');
$cache->set('key', 'new value'); // Écrase l'ancienne

// TTL en secondes (int)
$cache->set('key', $value, 3600);     // 1 heure
$cache->set('key', $value, 60);       // 1 minute

// TTL via DateInterval
$cache->set('key', $value, new DateInterval('PT1H'));  // 1 heure
$cache->set('key', $value, new DateInterval('P1D'));   // 1 jour

// Pas de TTL (null = valeur par défaut de la config)
$cache->set('key', $value, null);

// Expiration désactivée (0)
$cache->set('key', $value, 0);

// Stocker pour 1 seconde
$cache->set('expiring_key', 'temporary', 1);

// Immédiatement disponible
echo $cache->get('expiring_key'); // 'temporary'

// Attendre l'expiration
sleep(2);

// Plus disponible
echo $cache->get('expiring_key', 'default'); // 'default'
$cache->has('expiring_key'); // false

// config/jsonl-cache.php
'default_ttl' => 3600,  // 1 heure par défaut

// Utilisation
$cache->set('key', $value); // Expire dans 1 heure
$cache->set('key', $value, 0); // Jamais

// Aliases disponibles
$cache = app(JsonlCacheInterface::class);
$cache = app('jsonl-cache');



namespace App\Http\Controllers;

use AndyDefer\JsonlCache\Contracts\JsonlCacheInterface;
use App\Models\User;

final class UserController extends Controller
{
    private const CACHE_TTL = 300; // 5 minutes

    public function __construct(
        private readonly JsonlCacheInterface $cache,
    ) {}

    public function show(int $id): JsonResponse
    {
        $cacheKey = "user_{$id}";

        // Tentative de lecture du cache
        $user = $this->cache->get($cacheKey);

        if ($user === null) {
            $user = User::find($id);
            $this->cache->set($cacheKey, $user->toArray(), self::CACHE_TTL);
        }

        return response()->json($user);
    }

    public function update(int $id, Request $request): JsonResponse
    {
        // Mise à jour en base...
        $user = User::find($id);
        $user->update($request->validated());

        // Invalidation du cache
        $this->cache->delete("user_{$id}");

        return response()->json(['message' => 'Updated']);
    }
}



namespace App\Services;

use AndyDefer\JsonlCache\Contracts\JsonlCacheInterface;

final class WeatherService
{
    private const CACHE_TTL = 1800; // 30 minutes

    public function __construct(
        private readonly JsonlCacheInterface $cache,
        private readonly WeatherApiClient $api,
    ) {}

    public function getForecast(string $city): array
    {
        $cacheKey = "weather_{$city}";

        $forecast = $this->cache->get($cacheKey);
        if ($forecast !== null) {
            return $forecast;
        }

        $forecast = $this->api->fetchForecast($city);
        $this->cache->set($cacheKey, $forecast, self::CACHE_TTL);

        return $forecast;
    }
}



namespace Tests\Unit;

use AndyDefer\JsonlCache\Services\JsonlCacheService;
use Tests\TestCase;

final class CacheTest extends TestCase
{
    private JsonlCacheService $cache;

    protected function setUp(): void
    {
        parent::setUp();
        $this->cache = app(JsonlCacheInterface::class);
    }

    public function test_cache_set_and_get(): void
    {
        $key = 'test_key';
        $value = ['name' => 'John', 'email' => '[email protected]'];

        $this->cache->set($key, $value);
        $cached = $this->cache->get($key);

        $this->assertEquals($value, $cached);
    }

    public function test_cache_ttl(): void
    {
        $key = 'expiring_key';
        $value = 'temporary';

        $this->cache->set($key, $value, 1);
        $this->assertEquals($value, $this->cache->get($key));

        sleep(2);
        $this->assertNull($this->cache->get($key));
    }

    public function test_cache_delete(): void
    {
        $key = 'to_delete';
        $this->cache->set($key, 'value');
        $this->assertTrue($this->cache->has($key));

        $this->cache->delete($key);
        $this->assertFalse($this->cache->has($key));
    }
}
bash
php artisan vendor:publish --tag=jsonl-cache-config

set($key, $value, $ttl)
    │
    ├── normalizeKey() → ajout préfixe, hash si >64
    ├── getTtlSeconds() → conversion TTL
    ├── createExpiresAt() → DateTimeVO
    ├── json_encode($value) → sérialisation
    ├── Suppression ancien fichier
    ├── Création CacheRecord
    └── jsonl->write() → écriture JSONL