PHPackages                             phpixie/cache - 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. phpixie/cache

ActiveLibrary[Caching](/categories/caching)

phpixie/cache
=============

Cache library for PHPixie

3.3.1(6y ago)721.0k51BSD-3-ClausePHP

Since Apr 5Pushed 6y ago1 watchersCompare

[ Source](https://github.com/PHPixie/Cache)[ Packagist](https://packagist.org/packages/phpixie/cache)[ Docs](http://phpixie.com)[ RSS](/packages/phpixie-cache/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (5)Dependencies (6)Versions (12)Used By (1)

Cache
=====

[](#cache)

PHPixie Cache library

[![Build Status](https://camo.githubusercontent.com/7009225293a270bfca63b28a8455a780f75b03cd6d4cdb5917339bd9f329e6f5/68747470733a2f2f7472617669732d63692e6f72672f504850697869652f43616368652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/PHPixie/Cache)[![Author](https://camo.githubusercontent.com/24a0a94bb83eb81ba03c32074967dc730174cfd2849e984169db461d955cdbb9/687474703a2f2f696d672e736869656c64732e696f2f62616467652f617574686f722d40647261636f6e792d626c75652e7376673f7374796c653d666c61742d737175617265)](https://twitter.com/dracony)[![Source Code](https://camo.githubusercontent.com/4dc71b05e35fd3e6d4be7703ae814b2f0aeb905282c8b309619cab1fba7725be/687474703a2f2f696d672e736869656c64732e696f2f62616467652f736f757263652d706870697869652f63616368652d626c75652e7376673f7374796c653d666c61742d737175617265)](https://github.com/phpixie/cache)[![Software License](https://camo.githubusercontent.com/b60331a2084501dc07cf6d6964c0da58dd005d89c45cf3b28b4b22b60f5ec00f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4253442d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](https://github.com/phpixie/cache/blob/master/LICENSE)

The PHPixie Cache component supports both PSR-6 and PSR-16 standards and also adds a few useful features.

Initializing
------------

[](#initializing)

If you are using the PHPixie framework the component is accessible via your builder and configured in `/assets/config/cache.php`.

```
$cache = $builder->components->cache();
```

Like all the other PHPixie components you can use it without the framework, in that case initialize it like so:

```
$slice = new \PHPixie\Slice();
$config = $slice->arrayData([
     // configuration
    'default' => [
         'driver' => 'memory'
    ]
]);

// Optional dependency if you want to use file cache.
// This defines the root folder for file based drivers.
$filesystem = new \PHPixie\Filesystem();
$root = $filesystem->root('/tmp/cache/');

$cache = new \PHPixie\Cache($config, $root);
```

Configuration
-------------

[](#configuration)

Similarly to how you configure database connections, you can define multiple storage configurations using the available drivers: *void*, *memory*, *phpfile*, *memcached* and *redis*:

```
return [
    'default' => [
        // Doesn't store anything
        'driver' => 'void'
    ],

    'second' => [
        // Stores in a simple array
        'driver' => 'memory',

        /* Optional */

        /**
         * Default lifetime,
         * can be either number of seconds
         * or a DateInterval value, e.g. 'P1D' is one day.
         * Default is null, which is to store forever
         */
        'defaultExpiry' => 10,

        /**
         * A number between 1 and 1000 that
         * defines the frequency of garbage collection.
         * Defaults to 10, so 1% of all cache queries will
         * result in garbage collection to be run.
         */
        'cleanupProbability' => 10
    ],

    'third' => [
        // Values stored as .php files in folder
        'driver' => 'phpfile',

        // Relative to the /assets/cache folder
        'path'   => 'third',

        /* Optional */
        'defaultExpiry' => null,
        'cleanupProbability' => 10
    ],

    'fourth' => [
        'driver'  => 'memcached',

        /**
         * Same argument as to the Memcached::addServers() method,
         * but the port and weight parameters can be omitted and
         * default to 11211 and 1 respectively
         */
        'servers' => [
            ['127.0.0.1']
        ],

        /* Optional */
        'defaultExpiry' => null
    ],

    'fifth' => [
        'driver'  => 'redis',

        // Same argument as to the Predis\Client constructor
        'connection' => array(
            'scheme' => 'tcp',
            'host'   => '127.0.0.1',
            'port'   => 6379
        ),

        /* Optional */
        'defaultExpiry' => null
    ]
];
```

Usage
-----

[](#usage)

As mentioned PHPixie Cache supports both PSR-6 and the new simplified PSR-16. You will mostly use instances of the `PHPixie\Cache\Pool` interface:

```
namespace PHPixie\Cache;

use PHPixie\Cache\Pool\Prefixed;
use Psr\Cache\CacheItemPoolInterface;
use Psr\SimpleCache\CacheInterface;

// Inherits both PSR-6 and PSR-16
interface Pool extends CacheItemPoolInterface, CacheInterface
{
    /**
     * Creates a PSR-6 Item instance without trying to retrieve it from cache
     * @param string $key
     * @param mixed $value
     * @return Item
     */
    public function createItem($key, $value = null);

    /**
     * Creates a namespaced prefix pool.
     * We'll cover this later.
     * @param string $prefix
     * @return Prefixed
     */
    public function prefixedPool($prefix);
}
```

Some examples:

```
// Getting one of the defined storages
$storage = $cache->storage('second');

// PSR-6
public function getFairies()
{
    $item = $this->storage->getItem('fairies');
    if (!$item->isHit()) {
        $fairies = $this->generateFairies();
        $item->set($fairies);
        $item->expiresAfter(100);
        $this->storage->save($item);
    }
    return $item->get();
}

// PSR-16
public function getFairies()
{
    $fairies = $this->storage->get('fairies');
    if($fairies === null) {
         $fairies = $this->buildFairies();
         $this->storage->set('fairies', $fairies, 100);
    }
    return $fairies;
}
```

There's no point to rewrite here all the usage examples for these PSRs which already have great documentation. The additional methods like `delete`, `clear`, etc. are very intuitive easy to find in PSR docs and by using IDE hints. Let's instead focus on some unique features.

Prefixed pools
--------------

[](#prefixed-pools)

When multiple parts of the application use the same cash storage a common practice is to prefix keys. How often have you seen code like this:

```
$key = 'article-'.$id;
$article = $cache->get($key);
```

If these entities are cached in different parts of the application you have to make sure you are always using the same prefix or even abstract this logic into a separate service. PHPixie Cache solves this problem using a prefixed pools that proxy requests to the storage automatically prefixing the keys:

```
$storage = $cache->storage('default');
$articlesPool = $storage->prefixedPool('article');

$articlesPool->set($article->id, $article->html());

// same as
$storage ->set('article.'.$article->id, $article->html());
```

As you probably guessed such pools also implement the same `PHPixie\Cache\Pool` interface as the storages and can themselves be prefixed thus creating a hierarchy. They can be used to define different pools for different entities and also make it easy to later switch some of them to actual separate storages if needed. For example you can start out with one cache storage and multiple prefixed pools and expand easily when your application grows.

Simple usage without storages
-----------------------------

[](#simple-usage-without-storages)

The `PHPixie\Cache` class itself also implements the `Pool` interface and will proxy requests to the default cache storage. This makes the component easier to use in application with only one cache storage:

```
// instead of
$cache->storage('default')->get('fairy');

// just use
$cache->get('fairy');
```

Not hashing the keys
--------------------

[](#not-hashing-the-keys)

Most filesystem caches hash the key to generate the appropriate file name, this is done to protect you from using keys that contain characters not supported by the filesystem. In reality most people use alphanumeric cache keys anyway and hashing these provides no real value but makes cache files harder to inspect and makes a slight impact on the application performance. PHPixie Cache uses raw keys for filenames, although hashing can easily be introduced if required.

Optimized file cache
--------------------

[](#optimized-file-cache)

Most cache libraries serialize the value together with the expiry timestamp to store it in a file cache. This approach has two drawbacks: everytime you read the value you have to deserialize it which impacts performance when used frequently, also to just check if the cache has not yet expired you have to deserialize the entire file, which is wasteful if the actual value is not used afterwards. So how does PHPixie Cache solve these? Let's look at an example of a cached file:

```
