PHP code example of coroq / with-cache

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

    

coroq / with-cache example snippets




use Coroq\Cache\WithCache;
use Psr\Cache\CacheItemPoolInterface;

// Your existing interface
interface UserRepository {
    public function findById(int $id): ?User;
}

// Your existing implementation (no caching logic here)
class DatabaseUserRepository implements UserRepository {
    public function findById(int $id): ?User {
        // fetch from database
    }
}

// Caching decorator - implements same interface
class CachedUserRepository implements UserRepository {
    use WithCache;  // this library

    public function __construct(
        UserRepository $origin,           // the real repository
        CacheItemPoolInterface $cache,    // PSR-6 cache pool
    ) {
        $this->setCacheOrigin($origin);
        $this->setCachePool($cache);
    }

    public function findById(int $id): ?User {
        // delegates to origin, caches the result
        return $this->withCache();
    }
}

// Usage
$repository = new CachedUserRepository(
    new DatabaseUserRepository($pdo),
    $cachePool,
);
$user = $repository->findById(1);  // calls database
$user = $repository->findById(1);  // returns cached result
$user = $repository->findById(2);  // different argument, calls database

class CachedProductService implements ProductService {
    use WithCache;

    public function __construct(ProductService $origin, CacheItemPoolInterface $cache) {
        $this->setCacheOrigin($origin);
        $this->setCachePool($cache);
    }

    public function getById(int $id): ?Product {
        return $this->withCache();
    }

    public function getPopular(int $limit): array {
        return $this->withCache();
    }
}

public function getById(int $id): ?Product {
    return $this->withoutCache();  // always calls origin
}

use Psr\Cache\CacheException;

public function getById(int $id): ?Product {
    try {
        return $this->withCache();
    } catch (CacheException) {
        // fall back to origin on cache failure
        return $this->withoutCache();
    }
}

class CachedProductService implements ProductService {
    use WithCache;

    // ...

    protected function getCacheTtl(string $methodName, array $arguments, mixed $result): ?int {
        // return seconds, or null for no expiration
        return match($methodName) {
            'getPopular' => 300,      // 5 minutes
            'getById' => 3600,        // 1 hour
            default => null,
        };
    }
}

protected function getCacheTtl(string $methodName, array $arguments, mixed $result): ?int {
    if ($result === null) {
        return 60;  // cache "not found" briefly
    }
    return 3600;
}

protected function makeCacheKey(string $methodName, array $arguments): string {
    // default: sha1(class + method + serialized arguments)
    return "product.$methodName." . sha1(serialize($arguments));
}

public static function create(): self {
    return DatabaseUserRepository::create();
}

class CachedUserRepository implements UserRepository {
    use WithCache;

    // ...

    public function findById(int $id): ?User {
        return $this->withCache();
    }

    public function update(int $id, array $data): void {
        $this->withoutCache();
        $this->deleteCacheItem('findById', $id);
    }

    public function importFromCsv(string $path): void {
        $this->withoutCache();
        $this->clearCache();  // bulk operation, clear everything
    }
}