ophelios/php-apcu-cache

Simple APCu cache strategy compatible with PSR-16 for PHP.

1.0.0 2025-09-12 14:57 UTC

This package is auto-updated.

Last update: 2025-09-12 15:04:38 UTC


README

Maintainability Code Coverage

A tiny, dependency-free APCu cache implementation compatible with PSR-16 (Simple Cache) for PHP. It provides a thin wrapper around APCu functions with sensible key validation and TTL handling.

Features

  • PSR-16 compliant interface (get/set/delete/has and multi-operations)
  • APCu-backed, in-memory, super fast
  • TTL support via integers or DateInterval
  • Strict key validation per PSR-16 (forbidden characters: { } ( ) / \ @ : and empty keys)
  • Utility to list current APCu cache entries (ApcuCache::getList)

Requirements

  • PHP 8.4+
  • APCu extension enabled at runtime

Note: The test suite ships with a lightweight APCu polyfill so tests can run without the APCu extension. In production, you must have APCu installed and enabled.

Installation

Install with Composer:

composer require ophelios/php-apcu-cache

Quick start

use Cache\ApcuCache;

$cache = new ApcuCache();

// Set and get
$cache->set('greeting', 'hello world');
echo $cache->get('greeting'); // hello world

// Default value if missing
echo $cache->get('missing', 'default'); // default

// TTL as seconds
$cache->set('token', 'abc', 300); // 5 minutes

// TTL as DateInterval
$cache->set('short', 'value', new DateInterval('PT30S'));

// Existence
if ($cache->has('token')) {
    // ...
}

// Delete and clear
$cache->delete('token');
$cache->clear();

Multi operations

use Cache\ApcuCache;

$cache = new ApcuCache();
$cache->setMultiple([
    'a' => 1,
    'b' => 2,
]);

$values = $cache->getMultiple(['a', 'b', 'c'], 'x');
// ['a' => 1, 'b' => 2, 'c' => 'x']

$cache->deleteMultiple(['a', 'b']);

API notes

  • Key validation: Empty keys or keys containing any of { } ( ) / \\ @ : will throw Cache\\Exceptions\\InvalidArgumentException.
  • TTL conversion:
    • null means no expiration (APCu 0)
    • 0 is treated as expired (-1 internally)
    • Values > 30 days are converted to absolute timestamps
  • Availability: You can check if APCu is enabled using ApcuCache::isAvailable().
  • Listing cache: ApcuCache::getList() returns APCu cache entries (best-effort; structure depends on APCu).

Testing

This project uses PHPUnit 10.

Run tests:

vendor/bin/phpunit

Code coverage requires Xdebug or PCOV. If available, you can run:

XDEBUG_MODE=coverage vendor/bin/phpunit

Contributing

Contributions are welcome!

  • Open an issue for bugs or feature requests.
  • Submit a PR with a clear description and tests.

Dev setup:

  • Install dependencies: composer install
  • Run tests: vendor/bin/phpunit

License

MIT License © 2025 Ophelios. See LICENSE for details.