PHPackages                             talesoft/tale-cache-core - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Caching](/categories/caching)
4. /
5. talesoft/tale-cache-core

ActiveLibrary[Caching](/categories/caching)

talesoft/tale-cache-core
========================

A PSR-6 (Cache) and PSR-16 (SimpleCache) starter

0.1.0(7y ago)042MITPHPPHP &gt;=7.1.0

Since Jan 21Pushed 7y ago3 watchersCompare

[ Source](https://github.com/Talesoft/tale-cache-core)[ Packagist](https://packagist.org/packages/talesoft/tale-cache-core)[ Docs](http://docs.talesoft.codes/php/tale/cache-null-cache)[ RSS](/packages/talesoft-tale-cache-core/feed)WikiDiscussions master Synced 4d ago

READMEChangelog (1)Dependencies (3)Versions (2)Used By (0)

[![Packagist](https://camo.githubusercontent.com/f9df01c755e5307ad592f6ebc6dee970bd9cea9606a616a803ab8213a846d06b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f74616c65736f66742f74616c652d63616368652d636f72652e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/talesoft/tale-cache-core)[![License](https://camo.githubusercontent.com/3e988a31e4216e1be82ab2371856448f9ad1a538ec8be9a429550fb15720179d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f54616c65736f66742f74616c652d63616368652d636f72652e7376673f7374796c653d666f722d7468652d6261646765)](https://github.com/Talesoft/tale-cache-core/blob/master/LICENSE.md)[![CI](https://camo.githubusercontent.com/97d4f43945fc72f3ba5b71f020ec8979eeb79450a9fb6ca8438c12f90befd0fa/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f54616c65736f66742f74616c652d63616368652d636f72652e7376673f7374796c653d666f722d7468652d6261646765)](https://travis-ci.org/Talesoft/tale-cache-core)[![Coverage](https://camo.githubusercontent.com/9395fed6ad3a5d935b3d513cee8406200500681199d06ddf4200ff719a3af309/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636c696d6174652f636f7665726167652f54616c65736f66742f74616c652d63616368652d636f72652e7376673f7374796c653d666f722d7468652d6261646765)](https://codeclimate.com/github/Talesoft/tale-cache-core)

Tale Cache Core
===============

[](#tale-cache-core)

What is Tale Cache Core?
------------------------

[](#what-is-tale-cache-core)

Tale Cache Core is a basic extension of the PSR-6 and PSR-16 caching standards combined into a single library.

It acts as a base for libraries to be compatible to PSR-6 and PSR-16 caches without relying on heavy dependencies and also acts as a base for the Tale Cache library.

Furthermore, it tries to fix a single problem with the standard PSR cache specifications.

Installation
------------

[](#installation)

```
composer require talesoft/tale-cache-core
```

Usage
-----

[](#usage)

### PSR-6 to PSR-16 adapter

[](#psr-6-to-psr-16-adapter)

Easily use PSR-6 cache pools in your applications or libraries preferring PSR-16 by using `Tale\Cache\PoolCache`

```
use Tale\Cache\PoolCache;

$pool = new RedisCachePool(); //Create some PSR-6 CacheItemPool

$cache = new PoolCache($pool);
//$cache is now a PSR-16 cache

$data = $cache->get('some.key');
if ($data === null) {

    $data = ...; //Generate $data somehow
    $cache->set('some.key', $data);
}

//$data is now a cached value
```

### Null Cache and Runtime Cache for library authors

[](#null-cache-and-runtime-cache-for-library-authors)

Sometimes library authors want to make their libraries caching compatible, but don't want to implement a whole caching implementation with it. While interfaces work really well for that, they can only be represented as optional dependencies, when sometimes what you really want is a required dependency on a cache or test against a mocked implementation. A real implementation also avoids needing to make your properties nullable or do null-checks on optional dependencies all the time, so you avoid a lot of defensive programming with null checks

Tale Cache Core provides two lightweight, simple implementations of a PSR-6 cache pool that can be used as default values and work like normal caches, just that they don't really do anything

Imagine a service that looks like this:

```
use Psr\Cache\CacheItemPoolInterface;

final class MyService
{
    /** @var CacheItemPoolInterface */
    private $cachePool;

    public function __construct(CacheItemPoolInterface $cachePool)
    {
        $this->cachePool = $cachePool;
    }

    public function getCachePool(): CacheItemPoolInterface
    {
        return $this->cachePool;
    }

    public function doStuff(): void
    {
        $metadataItem = $this->cachePool->getItem('metadata');
        if (!$metadataItem->isHit()) {
            $metadataItem
                ->expiresAfter(new \DateInterval('P2D'))
                ->set($this->generateHeavyMetadata());

            $this->cachePool->save($metadataItem);
        }

        $metadata = $metadataItem->get();
        //Do something with $metadata
    }
}
```

If you might want to test against this or instantiate it somewhere, you can either use the `NullPool`

```
use Tale\Cache\Pool\NullPool;

$myService = new MyService(new NullPool());

$myService->doStuff();
```

This will basically just work like a completely disabled cache.

If you want to have some runtime caching so that cache items are not generated over and over again, you can also use the `RuntimePool`, which caches values as long as the process is there

```
use Tale\Cache\Pool\RuntimePool;

$myService = new MyService(new RuntimePool());

$myService->doStuff();
$myService->doStuff(); //This will be faster, as values are cached during runtime
```

If you still want optional dependencies, but you want to avoid defensive null-checks all over your library code, you can just default the value with a null-coalesce operator

```
public function __construct(CacheItemPoolInterface $cachePool = null)
{
    $this->cachePool = $cachePool ?? new NullPool();
}
```

### Easy custom Cache Pool implementation

[](#easy-custom-cache-pool-implementation)

Tale Cache Core takes some of the work you require when wanting to write PSR-6 compatible cache pools. As an example we will implement an own file cache with Tale Cache Core:

```
use Tale\Cache\Pool\AbstractPool;
use Tale\Cache\Item;

final class FilePool extends AbstractPool
{
    /** @var string */
    private $directory;

    public function __construct(string $directory)
    {
        $this->directory = $directory;
    }

    public function getItem($key): ItemInterface
    {
        $path = $this->getPathFromKey($key);
        if (file_exists($path)) {

            //Unserialize data from file
            [$ttl, $value] = unserialize(file_get_contents($path));

            //Check TTL
            if (time() < filemtime() + $ttl) {

                $expirationTime = new \DateTimeImmutable();
                $expirationTime->setTimestamp($expirationTime->getTimestamp() + $ttl);

                //Return a hit item
                return Item::createHit($key, $value, $expirationTime);
            }
        }
        //Create a miss
        return Item::createMiss($key);
    }

    public function clear(): bool
    {
        $files = glob("{$this->directory}/*.cache");
        $success = true;
        foreach ($files as $file) {
            if (!unlink($file)) {
                $success = false;
            }
        }
        return $success;
    }

    public function deleteItem($key): bool
    {
        $path = $this->getPathFromKey($key);
        return unlink($path);
    }

    public function save(CacheItemInterface $item): bool
    {
        //Make sure that it's an (interopable) Tale\Cache\ItemInterface instance
        //including items from this instance (which makes it downwards PSR-6 compatible)
        $this->filterItem($item);

        $path = $this->getPathFromKey($item->getKey());

        //This ->getExpireTime() call here is what enables interopability
        $ttl = time() - $item->getExpireTime()->getTimestamp();

        return file_put_contents($path, serialize([$ttl, $item->get()])) !== false;
    }

    private function getPathFromKey($key): string
    {
        $hash = md5($key);
        return "{$this->directory}/{$hash}.cache";
    }
}
```

now you have a fully valid PSR-6 cache working with files

```
$pool = new FilePool('/my/cache');

$item = $pool->getItem('my.data');
if (!$item->isHit()) {
    //Generate $data somehow
    $data = ...;

    $item
        ->expiresAfter(new \DateInterval('P2D'))
        ->set($data);
    $pool->saveDeferred($item);
}

$cachedData = $item->get();

//At end of execution
$pool->commit();
```

### Interoperable Cache Items

[](#interoperable-cache-items)

Tale Cache Core extends the normal PSR-6/16 interfaces and adds a single method that provides the ability to have a single CacheItem implementation for all possible CachePools

New interfaces to code against (All are PSR-6/16 compatible):

```
Psr\SimpleCache\CacheInterface   => Tale\CacheInterface
    | No new methods

Psr\Cache\CacheItemPoolInterface => Tale\Cache\PoolInterface
    | getItem($key): Tale\Cache\ItemInterface (type narrowing)

Psr\Cache\CacheItemInterface     => Tale\Cache\ItemInterface
    | getExpirationTime(): ?DateTimeInterface

```

As you can see, the `Tale\Cache\ItemInterface` provides a single **new**method to the interfaces, which allows us to **retrieve** the specified expiration time of a cache item. This allows the `Tale\Cache\ItemInterface`to be absolutely interoperable between different Item Pool implementations.

**You can move items from one pool to another**:

```
$poolA = new SomeCachePool();
$poolB = new SomeOtherCachePool();

$item = $poolA->getItem('some.item');
if ($item->isHit()) {
    $poolA->deleteItem($item);
    $poolB->save($item); //Cache Item has been moved to poolB
}
```

This is possible because the Cache Item can finally be a normal DTO and doesn't need its pool to set its expiration time, the cached value is stored inside the item along with its key and TTL, so it can always be moved or copied to other item pools.

###  Health Score

22

—

LowBetter than 22% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

2671d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/75a80e0830e63c723808d021d3a1648a2643db60f4ac2e40842da05f227f956b?d=identicon)[TorbenKoehn](/maintainers/TorbenKoehn)

---

Top Contributors

[![TorbenKoehn](https://avatars.githubusercontent.com/u/1403556?v=4)](https://github.com/TorbenKoehn "TorbenKoehn (6 commits)")

---

Tags

psr-6null-cacheruntime-cachecache item pool

### Embed Badge

![Health badge](/badges/talesoft-tale-cache-core/health.svg)

```
[![Health](https://phpackages.com/badges/talesoft-tale-cache-core/health.svg)](https://phpackages.com/packages/talesoft-tale-cache-core)
```

###  Alternatives

[laminas/laminas-cache

Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

1076.9M130](/packages/laminas-laminas-cache)[cache/adapter-common

Common classes for PSR-6 adapters

11124.4M38](/packages/cache-adapter-common)[cache/filesystem-adapter

A PSR-6 cache implementation using filesystem. This implementation supports tags

705.8M82](/packages/cache-filesystem-adapter)[cache/array-adapter

A PSR-6 cache implementation using a php array. This implementation supports tags

548.3M151](/packages/cache-array-adapter)[cache/redis-adapter

A PSR-6 cache implementation using Redis (PhpRedis). This implementation supports tags

523.9M27](/packages/cache-redis-adapter)[cache/simple-cache-bridge

A PSR-6 bridge to PSR-16. This will make any PSR-6 cache compatible with SimpleCache.

423.1M27](/packages/cache-simple-cache-bridge)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
