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

ActiveLibrary[Caching](/categories/caching)

shieldon/simple-cache
=====================

PSR-16 simple cache drivers for PHP.

1.3.4(2y ago)8814.3k2[1 issues](https://github.com/terrylinooo/simple-cache/issues)4MITPHPPHP &gt;=7.1.0CI failing

Since Sep 24Pushed 2y ago3 watchersCompare

[ Source](https://github.com/terrylinooo/simple-cache)[ Packagist](https://packagist.org/packages/shieldon/simple-cache)[ Docs](https://github.com/terrylinooo/simple-cache)[ RSS](/packages/shieldon-simple-cache/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (8)Dependencies (2)Versions (10)Used By (4)

PSR-16 Simple Cache
===================

[](#psr-16-simple-cache)

GitHub ActionTravis CIScrutinizer CICode CoverageCode Quality[![build](https://github.com/terrylinooo/simple-cache/workflows/build/badge.svg?branch=master)](https://github.com/terrylinooo/simple-cache/workflows/build/badge.svg?branch=master)[![Build Status](https://camo.githubusercontent.com/e96a56756974a3de41ee28221f2366caec7991fa06b4eb2bb5d03bbb5db9f02b/68747470733a2f2f7472617669732d63692e6f72672f74657272796c696e6f6f6f2f73696d706c652d63616368652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/terrylinooo/simple-cache)[![Build Status](https://camo.githubusercontent.com/11649ead05bd9f4663c03d5d4ba1bb86b0da932b05280d9e2c802c4639f71e33/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f74657272796c696e6f6f6f2f73696d706c652d63616368652f6261646765732f6275696c642e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/terrylinooo/simple-cache/build-status/master)[![codecov](https://camo.githubusercontent.com/ba0796b2b97d928040aa7af4e148452661a7bfcfe258f70349b05872beea7618/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f74657272796c696e6f6f6f2f73696d706c652d63616368652f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://codecov.io/gh/terrylinooo/simple-cache)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/018ef2e0462784c190ab5f67e56306be7e216edf2ca9ad29ee034e405f2c661b/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f74657272796c696e6f6f6f2f73696d706c652d63616368652f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/terrylinooo/simple-cache/?branch=master)Caching, a common performance-boosting technique, is a staple feature in many frameworks and libraries. This interoperability allows libraries to utilize existing caching implementations rather than creating their own. PSR-6 has addressed this issue, but its formal and verbose nature complicates simple use cases. PSR-16 is a simpler approach seeks to create a streamlined standard interface for common situations, ensuring compatibility with PSR-6 in a straightforward manner.

***Showcase***

Simple Cache is utilized in [Cache Master](https://github.com/terrylinooo/cache-master), a [WordPress Cache Plugin](https://wordpress.org/plugins/cache-master/), and it performs excellently. Check it out if you're running WordPress sites; it won't let you down.

#### Built-in drivers:

[](#built-in-drivers)

The required parameters are marked by an asterisk (\*)

Driver name`($driver)`PHP modules`($config)`File`file`-`*storage`Redis`redis`redis`host`, `port`, `user`, `pass`, `unix_socket`MongoDB`mongo`mongodb`host`, `port`, `user`, `pass`, `dbname`, `collection`, `unix_socket`MySQL`mysql`pdo\_mysql`host`, `port`, `*user`, `*pass`, `*dbname`, `table`, `charset`SQLite`sqlite`pdo\_sqlite`*storage`APC`apc`apc-APCu`apcu`apcu-Memcache`memcache`memcache`host`, `port`, `unix_socket`LibMemcached`memcached`memcached`host`, `port`, `unix_socket`WinCache`wincache`wincache-Note:

- **WinCache** is excluded from unit testing since it's only used on Windows, and the testing processes are done on Linux environment.
- `unix_socket` is empty by default, accepting the absolute path of the unix domain socket file. If it is set, `host` and `port` will be ignored.

The following command displays a list of installed PHP modules.

```
php -m
```

Before using, make sure the required PHP modules are installed on your system.

---

Table of Contents
-----------------

[](#table-of-contents)

- Install
- Usage
    - Cache
        - Built-in drivers
        - \_\_construct
        - $driver
        - $config
- API
    - set
    - get
    - has
    - delete
    - getMultiple
    - setMultiple
    - deleteMultiple
    - clear
    - clearExpiredItems `(Non-PSR-16)`
- Build Data Schema
    - MySQL
    - SQLite
- Garbage Collection
- Author
- License

---

Install
-------

[](#install)

```
composer require shieldon/simple-cache
```

Usage
-----

[](#usage)

### `Cache`

[](#cache)

Class `Cache` is an adapter that not only allows the implemented instance of `Psr\SimpleCache\CacheInterface`, but also has built-in drivers already.

#### \_\_construct(`$driver = ''`, `$config = []`)

[](#__constructdriver---config--)

Create a cache handler using the file driver.

Example:

```
$driver = new \Shieldon\SimpleCache\Cache('file', [
    'storage' => __DIR__ . '/../tmp'
]);
```

#### `$driver`

[](#driver)

(string|CacheInterface)

The class name of a built-in driver, or a PSR-16 driver that implements `Psr\SimpleCache\CacheInterface`.

#### `$config`

[](#config)

(array)

An array of parameters will be passed to a built-in driver.

Example:

*Redis*

```
$config = [
    'host' => '127.0.0.1',
    'port' => 6379,
    'user' => null,
    'pass' => null,
];
```

*File*

```
$config = [
    'storage' => '/tmp/simple-cache',
];
```

*Mysql*

```
$config = [
    'host'    => '127.0.0.1',
    'port'    => 3306,
    'user'    => null,
    'pass'    => null,
    'dbname'  => null,
    'table'   => 'cache_data',
    'charset' => 'utf8'
];
```

*Sqlite*

```
$config = [
    'storage' => '/tmp/simple-cache',
];
```

*Mongo*

```
$config = [
    'host'       => '127.0.0.1',
    'port'       => 27017,
    'user'       => null,
    'pass'       => null,
    'database'   => 'test',
    'collection' => 'cache_data',
];
```

*Memcache*, *Memcached*

```
$config = [
    'host' => '127.0.0.1',
    'port' => 11211,
];
```

---

API
---

[](#api)

Those API methods are defined on `Psr\SimpleCache\CacheInterface`. Please check out the [PSR-16 document](https://www.php-fig.org/psr/psr-16/) to get the detailed explanation.

- set
- get
- has
- delete
- setMultiple
- getMultiple
- deleteMultiple
- clear
- clearExpiredItems *(Non-PSR-16)*

### set

[](#set)

```
public function set(string $key, mixed value, $ttl = null);
```

Note that **$ttl** accepts `null`,`int`,`DateInterval`. The `null` means that the key never expires until deleted.

Example:

```
$cache->set('foo', 'bar', 300);
$cache->set('foo2', 'bar2');

$array = [
    'hello' => 'world',
    'yes' => 'Taiwan',
];

$cache->set('foo3', $array);
$cache->set('foo4', $array, 300);
```

### get

[](#get)

```
public function get(string $key, mixed $default = null): mixed
```

Example:

```
echo $cache->get('foo', 'placeholder');
// bar

sleep(301);

echo $cache->get('foo', 'placeholder');
// placeholder

echo $cache->get('foo');
// null

echo $cache->get('foo2', 'placeholder');
// bar2

$example = $cache->get('foo3', 'placeholder');
var_dump($example);
// string(11) "placeholder"

$example = $cache->get('foo4', 'placeholder');
var_dump($example);
/*
    array(2) {
    ["hello"]=>
    string(5) "world"
    ["yes"]=>
    string(6) "Taiwan"
    }
*/
```

### has

[](#has)

```
public function has(string $key): bool
```

Example:

```
if ($cache->has('foo3')) {
    echo 'foo3 exists.';
} else {
    echo 'foo3 does not exist.';
}
// foo3 exists.
```

### delete

[](#delete)

```
public function delete(string $key): bool
```

Example:

```
if ($cache->delete('foo3')) {
    echo 'foo3 has been deleted successfully.';
} else {
    echo 'Failed to delete key foo3.';
}
// foo3 has been deleted successfully.

if ($cache->has('foo3')) {
    echo 'foo3 exists.';
} else {
    echo 'foo3 does not exist.';
}
// foo3 does not exist.
```

### setMultiple

[](#setmultiple)

```
public function setMultiple(iterable $values, $ttl = null): bool
```

Note that **$ttl** accepts `null`,`int`,`DateInterval`. The `null` means that the key never expires until deleted.

Example:

```
$array = [
    'bar' => 'foo',
    'bar2' => 'foo2',
];

$cache->setMultiple($array, 300);
```

### getMultiple

[](#getmultiple)

```
public function getMultiple(array $keys, mixed $default = null): iterable
```

Example:

```
$example = $cache->getMultiple(['bar', 'bar2', 'bar3'], 'hello');
var_dump($example);
/*
    array(3) {
    ["bar"]=>
    string(3) "foo"
    ["bar2"]=>
    string(4) "foo2"
    ["bar3"]=>
    string(5) "hello"
    }
*/
```

### deleteMultiple

[](#deletemultiple)

```
public function deleteMultiple(array $keys): bool
```

Example:

```
if ($cache->deleteMultiple(['bar', 'bar2'])) {
    echo 'bar and bar2 have been deleted successfully.';
} else {
    echo 'Failed to delete keys bar or bar2.';
}
// bar and bar2 have been deleted successfully.

$example = $cache->getMultiple(['bar', 'bar2', 'bar3'], 'hello');
var_dump($example);
/*
    array(3) {
    ["bar"]=>
    string(5) "hello"
    ["bar2"]=>
    string(5) "hello"
    ["bar3"]=>
    string(5) "hello"
    }
*/
```

### clear

[](#clear)

```
public function clear(): bool
```

Example:

```
if ($cache->clear()) {
    echo 'All cached data has been deleted successfully.';
} else {
    echo 'Failed to delete the cached data.';
}
// All cached data has been deleted successfully.
```

### clearExpiredItems `Non-PSR-16`

[](#clearexpireditems-non-psr-16)

```
public function clearExpiredItems(): array
```

This method returns a list of deleted cache keys.

*Note*: **Redis** and **Memcache**, **Memcached** drivers will always return an empty array. See *Garbage Collection* section below.

Example:

```
$cache->set('foo', 'bar', 300);
$cache->set('foo2', 'bar2', 5);
$cache->set('foo3', 'bar3', 5);

sleep(6);

$expiredItems = $cache->clearExpiredItems();
var_dump($expiredItems);

/*
    array(2) {
    [0]=>
    string(4) "foo2"
    [1]=>
    string(4) "foo3"
    }
*/
```

---

Build Data Schema
-----------------

[](#build-data-schema)

The data schema needs to be built for the initial use of MySQL and SQLite drivers.

This API can be utilized for this purpose.

```
$cache->rebuild();
```

Or build it manually.

### MySQL

[](#mysql)

```
CREATE TABLE IF NOT EXISTS `cache_data` (
    `cache_key` varchar(40) NOT NULL,
    `cache_value` longtext,
    PRIMARY KEY (`cache_key`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
```

### SQLite

[](#sqlite)

```
CREATE TABLE IF NOT EXISTS cache_data (
    cache_key VARCHAR(40) PRIMARY KEY,
    cache_value LONGTEXT
);
```

---

Garbage Collection
------------------

[](#garbage-collection)

For built-in drivers, enabling garbage collection will automatically clear expired cache from your system.

Use the following parameters:

```
$config = [
    'gc_enable'      => true,
    'gc_divisor'     => 100, // default
    'gc_probability' => 1, // default
];
```

This implies a 1% probability of executing garbage collection. Avoid setting it to 100% as it will unnecessarily fetch and check all keys one by one.

Example:

```
$driver = new \Shieldon\SimpleCache\Cache('file', [
    'storage'   => __DIR__ . '/../tmp',
    'gc_enable' => true,
]);
```

You can just use the `gc_enable` to enable garbage collection.

### Note

[](#note)

For the **Redis**, **Memcache**, and **Memcached** drivers, this method isn't necessary as expired items are automatically cleared.

---

Contributing
------------

[](#contributing)

Thank you for your interest in contributing to our project! We welcome contributions from everyone. Before getting started, please take a moment to review the guidelines below:

### Guidelines

[](#guidelines)

- Fork the repository and create your branch from master.
- Make sure your code follows our coding style and conventions.
- Keep your code concise, well-documented, and modular.
- Write clear commit messages that describe the purpose of your changes.
- Test your changes thoroughly to ensure they don't introduce any new issues.
- Make sure your code builds successfully without any errors or warnings.
- Update relevant documentation, including README files if necessary.
- Submit a pull request (PR) to the master branch of the original repository.

### Code Testing

[](#code-testing)

We utilize a Docker image that includes various dependencies for our code testing. The image is based on `/tests/Fixture/docker/Dockerfile` and is preconfigured with the following components:

- Redis
- MongoDB
- MySQL
- PHP
- Memcached
- APCu

Follow the steps below to run the tests:

- Make sure you have Docker installed on your machine. If not, you can download and install it from the official Docker website.
- Navigate to the project directory and build the Docker image by running the following command: ```
    composer test:docker:build

    ```
- Once the Docker image is built, you can run the tests by executing the following command: ```
    composer test:docker:run

    ```
- Observe the test results and make note of any failures or errors. The output will be displayed in the terminal.

---

Author
------

[](#author)

- [Terry L.](https://terryl.in/) and contributers, such as [Jimmy](https://colocal.com) and others.

#### The Origin of this Library

[](#the-origin-of-this-library)

This PHP library was created for the [12th Ironman Game](https://ithelp.ithome.com.tw/2020-12th-ironman) competition, hosted by ITHelp, a Taiwanese IT community. My chosen topic was "Road to PHP Master - The Best Practice in Open Source Code", composed in traditional Chinese. You can read it [here](https://ithelp.ithome.com.tw/users/20111119/ironman/3269) if you're interested.

License
-------

[](#license)

MIT

###  Health Score

36

—

LowBetter than 79% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity38

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 98.6% 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 ~127 days

Recently: every ~243 days

Total

9

Last Release

1086d ago

### Community

Maintainers

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

---

Top Contributors

[![terrylinooo](https://avatars.githubusercontent.com/u/11989371?v=4)](https://github.com/terrylinooo "terrylinooo (138 commits)")[![PaulCapron](https://avatars.githubusercontent.com/u/14962577?v=4)](https://github.com/PaulCapron "PaulCapron (1 commits)")[![S1SYPHOS](https://avatars.githubusercontent.com/u/12161504?v=4)](https://github.com/S1SYPHOS "S1SYPHOS (1 commits)")

---

Tags

php-cachephp-mongodbphp-redispsr-16simple-cachepsr-16psr-6php cache

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/shieldon-simple-cache/health.svg)

```
[![Health](https://phpackages.com/badges/shieldon-simple-cache/health.svg)](https://phpackages.com/packages/shieldon-simple-cache)
```

###  Alternatives

[laminas/laminas-cache

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

1077.3M154](/packages/laminas-laminas-cache)[cache/simple-cache-bridge

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

433.3M28](/packages/cache-simple-cache-bridge)[codeigniter4/cache

PSR-6 and PSR-16 Cache Adapters for CodeIgniter 4

1422.1k](/packages/codeigniter4-cache)

PHPackages © 2026

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