Skip to content
cccskills
FreePublished on GitHub

acc-create-psr16-simple-cache

Generates PSR-16 Simple Cache implementation for PHP 8.5. Creates CacheInterface with get/set/delete operations and TTL handling. Includes unit tests.

The English summary is being prepared. Showing the original description.

Works withRedis
See how to install

Files included (1)

  • SKILL.md6.2 KB

SKILL.md (original)

Review the instructions the agent will receive before you install.

PSR-16 Simple Cache Generator

Overview

Generates PSR-16 compliant simple cache implementations for basic caching needs.

When to Use

  • Simple key-value caching
  • Performance-critical code paths
  • Minimal caching abstraction
  • Quick cache integration

Template: Array Cache

<?php

declare(strict_types=1);

namespace App\Infrastructure\Cache;

use DateInterval;
use DateTimeImmutable;
use Psr\SimpleCache\CacheInterface;

final class ArrayCache implements CacheInterface
{
    /** @var array<string, array{value: mixed, expiration: ?int}> */
    private array $cache = [];

    public function get(string $key, mixed $default = null): mixed
    {
        $this->validateKey($key);

        if (!isset($this->cache[$key])) {
            return $default;
        }

        $item = $this->cache[$key];

        if ($item['expiration'] !== null && $item['expiration'] < time()) {
            unset($this->cache[$key]);

            return $default;
        }

        return $item['value'];
    }

    public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool
    {
        $this->validateKey($key);

        $expiration = $this->calculateExpiration($ttl);

        $this->cache[$key] = [
            'value' => $value,
            'expiration' => $expiration,
        ];

        return true;
    }

    public function delete(string $key): bool
    {
        $this->validateKey($key);
        unset($this->cache[$key]);

        return true;
    }

    public function clear(): bool
    {
        $this->cache = [];

        return true;
    }

    public function getMultiple(iterable $keys, mixed $default = null): iterable
    {
        $result = [];

        foreach ($keys as $key) {
            $result[$key] = $this->get($key, $default);
        }

        return $result;
    }

    public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool
    {
        foreach ($values as $key => $value) {
            $this->set($key, $value, $ttl);
        }

        return true;
    }

    public function deleteMultiple(iterable $keys): bool
    {
        foreach ($keys as $key) {
            $this->delete($key);
        }

        return true;
    }

    public function has(string $key): bool
    {
        return $this->get($key, $this) !== $this;
    }

    private function calculateExpiration(null|int|DateInterval $ttl): ?int
    {
        if ($ttl === null) {
            return null;
        }

        if ($ttl instanceof DateInterval) {
            return (new DateTimeImmutable())->add($ttl)->getTimestamp();
        }

        return time() + $ttl;
    }

    private function validateKey(string $key): void
    {
        if ($key === '' || preg_match('/[{}()\/\\\\@:]/', $key)) {
            throw new InvalidArgumentException("Invalid cache key: {$key}");
        }
    }
}

Template: Redis Cache

<?php

declare(strict_types=1);

namespace App\Infrastructure\Cache;

use DateInterval;
use DateTimeImmutable;
use Psr\SimpleCache\CacheInterface;
use Redis;

final readonly class RedisCache implements CacheInterface
{
    public function __construct(
        private Redis $redis,
        private string $prefix = 'cache:',
    ) {
    }

    public function get(string $key, mixed $default = null): mixed
    {
        $value = $this->redis->get($this->prefix . $key);

        if ($value === false) {
            return $default;
        }

        return unserialize($value);
    }

    public function set(string $key, mixed $value, null|int|DateInterval $ttl = null): bool
    {
        $serialized = serialize($value);
        $fullKey = $this->prefix . $key;

        if ($ttl === null) {
            return $this->redis->set($fullKey, $serialized);
        }

        $seconds = $ttl instanceof DateInterval
            ? (new DateTimeImmutable())->add($ttl)->getTimestamp() - time()
            : $ttl;

        return $this->redis->setex($fullKey, $seconds, $serialized);
    }

    public function delete(string $key): bool
    {
        return $this->redis->del($this->prefix . $key) > 0;
    }

    public function clear(): bool
    {
        $keys = $this->redis->keys($this->prefix . '*');

        if (!empty($keys)) {
            $this->redis->del($keys);
        }

        return true;
    }

    public function getMultiple(iterable $keys, mixed $default = null): iterable
    {
        $result = [];

        foreach ($keys as $key) {
            $result[$key] = $this->get($key, $default);
        }

        return $result;
    }

    public function setMultiple(iterable $values, null|int|DateInterval $ttl = null): bool
    {
        foreach ($values as $key => $value) {
            $this->set($key, $value, $ttl);
        }

        return true;
    }

    public function deleteMultiple(iterable $keys): bool
    {
        foreach ($keys as $key) {
            $this->delete($key);
        }

        return true;
    }

    public function has(string $key): bool
    {
        return $this->redis->exists($this->prefix . $key) > 0;
    }
}

Template: Exceptions

<?php

declare(strict_types=1);

namespace App\Infrastructure\Cache;

use Psr\SimpleCache\CacheException as PsrCacheException;
use Psr\SimpleCache\InvalidArgumentException as PsrInvalidArgumentException;

final class CacheException extends \RuntimeException implements PsrCacheException
{
}

final class InvalidArgumentException extends \InvalidArgumentException implements PsrInvalidArgumentException
{
}

Usage Example

<?php

use App\Infrastructure\Cache\RedisCache;

$cache = new RedisCache($redis);

// Simple operations
$cache->set('user:123', $userData, 3600);
$user = $cache->get('user:123');

// Check existence
if ($cache->has('user:123')) {
    $cache->delete('user:123');
}

// Multiple operations
$cache->setMultiple([
    'config:app' => $appConfig,
    'config:db' => $dbConfig,
], 86400);

$configs = $cache->getMultiple(['config:app', 'config:db']);

Requirements

{
    "require": {
        "psr/simple-cache": "^3.0"
    }
}

Reviews

No reviews yet. Tell others what you thought.

Comments

No login needed. Share how it worked for you, ask a question, or note where it did not run.

No comments yet. Be the first to write one.

Comments are published right away. Do not include personal information such as email addresses or phone numbers. Up to 2 URLs.

0 / 1,000 characters

This form is protected by reCAPTCHA, and the Google Privacy Policy and Terms of Service apply.

More skills from this repository

Master backend architectures, REST API design, microservices, and server-side development across multiple languages. Use this as a central index to access specialized sub-skills.

The English summary is being prepared. Showing the original description.

MikeCheng1208/BattleTree2Updated Jul 22, 2026

在每次回复中使用固定前缀并列出本次实际参考的指令/文件,便于校验是否遵循上下文与规则。

The English summary is being prepared. Showing the original description.

MikeCheng1208/BattleTree2Updated Jul 22, 2026

Automate 21risk tasks via Rube MCP (Composio). Always search tools first for current schemas.

The English summary is being prepared. Showing the original description.

MikeCheng1208/BattleTree2Updated Jul 22, 2026

Automate 2chat tasks via Rube MCP (Composio). Always search tools first for current schemas.

The English summary is being prepared. Showing the original description.

MikeCheng1208/BattleTree2Updated Jul 22, 2026

Arquitecto de Soluciones Principal y Consultor Tecnológico de Andru.ia. Diagnostica y traza la hoja de ruta óptima para proyectos de IA en español.

The English summary is being prepared. Showing the original description.

MikeCheng1208/BattleTree2Updated Jul 22, 2026

[00] META. Orchestrate skills into dynamic chains for complex tasks. Analyzes the task, discovers available skills, builds an optimal chain, explains why each skill is needed, and executes step-by-step with user confirmation. Use for any complex task requiring multiple thinking/research/analysis steps. Triggers on "plan this", "how to approach", "what's the strategy", "build a plan", or any multi-step problem requiring skill orchestration.

The English summary is being prepared. Showing the original description.

MikeCheng1208/BattleTree2Updated Jul 22, 2026

See all skills by MikeCheng1208

Report a problem with this skill