PHPackages                             silentbyte/litecache - 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. silentbyte/litecache

ActiveLibrary[Caching](/categories/caching)

silentbyte/litecache
====================

A lightweight, easy-to-use, and straightforward caching library for PHP.

2.1.2(5y ago)1040MITPHPCI failing

Since Jan 4Pushed 5y ago2 watchersCompare

[ Source](https://github.com/SilentByte/litecache)[ Packagist](https://packagist.org/packages/silentbyte/litecache)[ Docs](https://github.com/SilentByte/litecache)[ RSS](/packages/silentbyte-litecache/feed)WikiDiscussions master Synced 2mo ago

READMEChangelogDependencies (6)Versions (10)Used By (0)

LiteCache 2.1
=============

[](#litecache-21)

[![Build Status](https://camo.githubusercontent.com/b54934071c02696f8aea6b5f8bede286350e089cdef51ca5ee88b5a4d96a3fcf/68747470733a2f2f7472617669732d63692e6f72672f53696c656e74427974652f6c69746563616368652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/SilentByte/litecache)[![Latest Stable Version](https://camo.githubusercontent.com/bdfa3a345a403aa07c1104eb5c503c87747523b54e0f7f2df8969a220055b586/687474703a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f73696c656e74627974652f6c69746563616368652e737667)](https://packagist.org/packages/silentbyte/litecache)[![MIT License](https://camo.githubusercontent.com/100dc28a5ba93243f079e1a372e19636ec4bc6b2445a282b04a0a62baab5d80e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542532304c6963656e73652d626c75652e737667)](https://opensource.org/licenses/MIT)

This is the official repository of the SilentByte LiteCache Library.

LiteCache is a lightweight, easy-to-use, and [PSR-16](http://www.php-fig.org/psr/psr-16/) compliant caching library for PHP 7.0+ that tries to utilize PHP's built in caching mechanisms. Advanced caching systems such as [Memcached](https://memcached.org/) are often not available on low-cost hosting providers. However, code/opcode caching is normally enabled to speed up execution. LiteCache leverages this functionality by generating `*.php` files for cached objects which are then optimized and cached by the execution environment.

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

[](#installation)

The easiest way to install the latest version of LiteCache is using [Composer](https://getcomposer.org/):

```
$ composer require silentbyte/litecache
```

More information can be found on [Packagist](https://packagist.org/packages/silentbyte/litecache).

If you would like to check out and include the source directly without using Composer, simply clone this repository:

```
$ git clone https://github.com/SilentByte/litecache.git
```

General Usage
-------------

[](#general-usage)

LiteCache implements [PSR-16](http://www.php-fig.org/psr/psr-16/) and thus provides a standardized API for storing and retrieving data. The full API documentation is available here: [LiteCache 2.0 API Documentation](https://docs.silentbyte.com/litecache/).

### Caching 101

[](#caching-101)

Let's get started with the following basic example that demonstrates how to load and cache an application's configuration from a JSON file.

```
$cache = new \SilentByte\LiteCache\LiteCache();

$config = $cache->get('config');
if ($config === null) {
    $config = json_decode(file_get_contents('config.json'), true);
    $cache->set('config', $config);
}

var_dump($config);
```

The methods `$cache->get($key, $default = null)` and `$cache->set($key, $value, $ttl = null)` are used to retrieve and save the configuration from and to the cache under the unique name `config`, respecting the defined TTL. In case of a *cache miss*, the data will be loaded from the actual JSON file and is then immediately cached.

Without the cache as an intermediary layer, the JSON file would have to be loaded and parsed upon every request. LiteCache avoids this issue by utilizing PHP's code caching mechanisms.

The library is designed to cache data of any kind, including integers, floats, strings, booleans, arrays, and objects. In addition, LiteCache provides the ability to cache files and content from the output buffer to provide faster access.

### Advanced Caching

[](#advanced-caching)

The main function for storing and retrieving objects to and from the cache is the method `$cache->cache($name, $producer, $ttl)`. The first parameter `$name` is the unique name of the object to be stored. `$producer` is a generator function that will be called if the object has expired or not yet been cached. The return value of this `callable` will be stored in the cache. `$ttl`, or *time-to-live*, defines the number of seconds before the objects expires. If `$ttl` is not specified, the cache's default time-to-live will be used (in the listed code below, that is 10 minutes).

The following example issues a Github API request using cURL and caches the result for 10 minutes. When the code is run for the first time, it will fetch the data from the Github server. Subsequent calls to the script will access the cached value without issuing a time-expensive request.

```
// Create the cache object with a customized configuration.
$cache = new \SilentByte\LiteCache\LiteCache([
    // Specify the caching directory.
    'directory' => '.litecache',

    // Make cached objects expire after 10 minutes.
    'ttl' => '10 minutes'
]);

// Issue a Github API request and cache it under the specified name ('git-request').
// Subsequent calls to $cache->cache() will be fetched from cache;
// after expiration, a new request will be issued.
$response = $cache->cache('git-request', function () {
    $ch = curl_init('https://api.github.com/users/SilentByte');
    curl_setopt($ch, CURLOPT_USERAGENT, 'SilentByte/litecache');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    return json_decode(curl_exec($ch));
});

echo "Name: ", $response->login, "\n",
     "Website: ", $response->blog, "\n",
     "Update: ", $response->updated_at, "\n";
```

Further examples can be found in the `./examples/` directory within this repository.

### Using Producers

[](#using-producers)

LiteCache's `cache($key, $producer, $ttl)` method uses producers (implemented as function objects) that yield the data for storage in the cache. A couple of useful producers are already shipped with LiteCache, namely: `FileProducer`, `IniProducer`, `JsonProducer`, and `OutputProducer`.

Using the `IniProducer` with the following `*.ini` file...

```
[server]
host = myhost.test.com
user = root
password = root
```

...and this code...

```
use SilentByte\LiteCache\IniProducer;
use SilentByte\LiteCache\LiteCache;

// Create the cache object with a customized configuration.
$cache = new LiteCache([
    // Cache objects permanently.
    'ttl' => LiteCache::EXPIRE_NEVER
]);

// Load the specified INI configuration file and cache it.
$config = $cache->cache('ini-cache', new IniProducer('./sample_data/test_ini.ini'));

echo "Host: ", $config['server']['host'], "\n",
     "User: ", $config['server']['user'], "\n",
     "Password: ", $config['server']['password'], "\n";
```

...will result in the configuration file being cached for all further calls of the script, thus avoiding unnecessary parsing on every request. The same concept applies to the other types or producers.

The same concept can be applied to cache PHP's output, e.g. caching a web page in order to avoid having to re-render it upon every request. The easiest way to achieve this is by using the integrated `OutputProducer`:

```
use SilentByte\LiteCache\LiteCache;
use SilentByte\LiteCache\OutputProducer;

// Create the cache object with a customized configuration.
$cache = new LiteCache([
    // Specify the caching directory.
    'directory' => '.litecache',

    // Cache objects for 30 seconds.
    'ttl'       => '30 seconds'
]);

// Load the specified file and cache it.
$output = $cache->cache('script-cache', new OutputProducer(function () {
    include('./sample_data/slow_script.php');
}));

echo "---- (Script Output) -------------------\n";
echo $output;
echo "---------------------------------------\n";
```

All output from the included PHP script (e.g. generated via `echo`) will be cached for 30 seconds. If you are using a templating engine such as [Twig](http://twig.sensiolabs.org/), `OutputProducer` can be used to cache the rendered page. In case the data is directly available as a string, a simple call to `$cache->set($key, $value)` will suffice.

See the `./examples/` folder for more details.

### Options

[](#options)

LiteCache's constructor accepts an array that specifies user-defined options.

```
// LiteCache 2.1 Default Options.
$options = [
    'directory'   => '.litecache',
    'subdivision' => false,
    'pool'        => 'default',
    'ttl'         => LiteCache::EXPIRE_NEVER,
    'logger'      => null
];

$cache = new LiteCache($options);
```

OptionTypeDescriptiondirectorystringLocation (path) indicating where the cache files are to be stored.subdivisionboolPlaces cache files into different sub-directories to avoid having many files in the same directory.poolstringDefines the name of the cache pool. A pool is a logical separation of cache objects. Cache objects in different pools are independent of each other and may thus share the same unique name. See [PSR-6 #pool](http://www.php-fig.org/psr/psr-6/#pool).ttlnull
int
string
DateIntervalTime-To-Live. Defines a time interval that signaling when cache objects expire by default. This value may be specified as an integer indicating seconds (e.g. 10), a time interval string (e.g '10 seconds'), an instance of DateInterval, or `LiteCache::EXPIRE_NEVER` / `LiteCache::EXPIRE_IMMEDIATELY`.loggerLoggerInterface
nullAn instance of a [PSR-3](http://www.php-fig.org/psr/psr-3/) compliant logger class (implementing `\Psr\Log\LoggerInterface`) that is used to receive logging information. May be `null` if not required.Contributing
------------

[](#contributing)

See [CONTRIBUTING.md](CONTRIBUTING.md).

Change Log
----------

[](#change-log)

See [CHANGELOG.md](CHANGELOG.md).

FAQ
---

[](#faq)

### Under what license is LiteCache released?

[](#under-what-license-is-litecache-released)

MIT license. Check out [LICENSE.txt](LICENSE.txt) for details. More information regarding the MIT license can be found here:

### How do I permanently cache static files, i.e. configuration files?

[](#how-do-i-permanently-cache-static-files-ie-configuration-files)

Setting the `$ttl` value to `LiteCache::EXPIRE_NEVER` will cause objects to remain in the cache until the cache file is deleted manually, either by physically deleting the file or by calling `$cache->delete($key)` or `$cache->clean()`.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity14

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity69

Established project with proven stability

 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

Every ~209 days

Recently: every ~355 days

Total

8

Last Release

1952d ago

Major Versions

1.x-dev → 2.02017-01-25

### Community

Maintainers

![](https://www.gravatar.com/avatar/b325c6b8b023f7df405d2bbd858d716059eb597ea7c32cc6baa5c259ec404b95?d=identicon)[silentbyte](/maintainers/silentbyte)

---

Top Contributors

[![SilentByte](https://avatars.githubusercontent.com/u/18737288?v=4)](https://github.com/SilentByte "SilentByte (105 commits)")

---

Tags

cache-storagepsr-16configcachecachingOpcache

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/silentbyte-litecache/health.svg)

```
[![Health](https://phpackages.com/badges/silentbyte-litecache/health.svg)](https://phpackages.com/packages/silentbyte-litecache)
```

###  Alternatives

[gordalina/cachetool

Manage your OPcache &amp; APCu cache through the CLI

1.8k3.7M5](/packages/gordalina-cachetool)[voku/simple-cache

Simple Cache library

322.5M7](/packages/voku-simple-cache)[mmamedov/page-cache

PageCache is a lightweight PHP library for full page cache. It uses various strategies to differentiate among separate versions of the same page.

7912.7k1](/packages/mmamedov-page-cache)[webarchitect609/bitrix-cache

Comfortable fluent interface for Bitrix cache. Anti-stampede cache protection.

2831.2k8](/packages/webarchitect609-bitrix-cache)[momentohq/client-sdk-php

PHP SDK for Momento, a serverless cache that automatically scales without any of the operational overhead required by traditional caching solutions.

1278.2k3](/packages/momentohq-client-sdk-php)[apix/simple-cache

The PSR-16 extension to Apix-Cache.

1017.4k](/packages/apix-simple-cache)

PHPackages © 2026

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