{"id":21850330,"url":"https://github.com/terrylinooo/simple-cache","last_synced_at":"2025-07-05T11:34:08.051Z","repository":{"id":49197400,"uuid":"295723076","full_name":"terrylinooo/simple-cache","owner":"terrylinooo","description":"PSR-16 simple cache drivers for PHP.","archived":false,"fork":false,"pushed_at":"2023-07-14T06:50:37.000Z","size":112,"stargazers_count":88,"open_issues_count":0,"forks_count":2,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-06-08T23:48:43.535Z","etag":null,"topics":["php-cache","php-mongodb","php-redis","psr-16","simple-cache"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/terrylinooo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2020-09-15T12:35:57.000Z","updated_at":"2024-11-20T14:01:56.000Z","dependencies_parsed_at":"2024-02-25T03:43:32.862Z","dependency_job_id":null,"html_url":"https://github.com/terrylinooo/simple-cache","commit_stats":{"total_commits":136,"total_committers":4,"mean_commits":34.0,"dds":"0.11764705882352944","last_synced_commit":"b8560f9828164daff0560fe97ffd9b246e81ed8e"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/terrylinooo/simple-cache","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terrylinooo%2Fsimple-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terrylinooo%2Fsimple-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terrylinooo%2Fsimple-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terrylinooo%2Fsimple-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/terrylinooo","download_url":"https://codeload.github.com/terrylinooo/simple-cache/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/terrylinooo%2Fsimple-cache/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263733640,"owners_count":23503197,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["php-cache","php-mongodb","php-redis","psr-16","simple-cache"],"created_at":"2024-11-28T00:17:06.753Z","updated_at":"2025-07-05T11:34:08.006Z","avatar_url":"https://github.com/terrylinooo.png","language":"PHP","readme":"# PSR-16 Simple Cache\n\n| GitHub Action | Travis CI |  Scrutinizer CI | Code Coverage | Code Quality |\n| ------------- | --------- | --------------- | ------------- | ------------ |\n| ![build](https://github.com/terrylinooo/simple-cache/workflows/build/badge.svg?branch=master) | [![Build Status](https://travis-ci.org/terrylinooo/simple-cache.svg?branch=master)](https://travis-ci.org/terrylinooo/simple-cache) | [![Build Status](https://scrutinizer-ci.com/g/terrylinooo/simple-cache/badges/build.png?b=master)](https://scrutinizer-ci.com/g/terrylinooo/simple-cache/build-status/master) |  [![codecov](https://scrutinizer-ci.com/g/terrylinooo/simple-cache/badges/coverage.png?b=master)](https://codecov.io/gh/terrylinooo/simple-cache) |  [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/terrylinooo/simple-cache/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/terrylinooo/simple-cache/?branch=master)\n\nCaching, 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.\n\n***Showcase***\n\nSimple 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.\n\n#### Built-in drivers:\n\nThe required parameters are marked by an asterisk (*)\n\n| Driver name  | `($driver)` | PHP modules | `($config)`                                                           |\n| ------------ | ----------- | ----------- | --------------------------------------------------------------------- |\n| File         | `file`      | -           | `*storage`                                                            |\n| Redis        | `redis`     | redis       | `host`, `port`, `user`, `pass`, `unix_socket`                         |\n| MongoDB      | `mongo`     | mongodb     | `host`, `port`, `user`, `pass`, `dbname`, `collection`, `unix_socket` |\n| MySQL        | `mysql`     | pdo_mysql   | `host`, `port`, `*user`, `*pass`, `*dbname`, `table`, `charset`       |\n| SQLite       | `sqlite`    | pdo_sqlite  | `*storage`                                                            |\n| APC          | `apc`       | apc         | -                                                                     |\n| APCu         | `apcu`      | apcu        | -                                                                     |\n| Memcache     | `memcache`  | memcache    | `host`, `port`, `unix_socket`                                         |\n| LibMemcached | `memcached` | memcached   | `host`, `port`, `unix_socket`                                         |\n| WinCache     | `wincache`  | wincache    | -                                                                     |\n\nNote: \n\n- **WinCache** is excluded from unit testing since it's only used on Windows, and the testing processes are done on Linux environment.\n- `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.\n\nThe following command displays a list of installed PHP modules.\n\n```bash\nphp -m\n```\nBefore using, make sure the required PHP modules are installed on your system.\n\n---\n\n## Table of Contents\n\n- Install\n- Usage\n    - Cache\n        - Built-in drivers\n        - __construct\n        - $driver\n        - $config\n- API\n    - set\n    - get\n    - has\n    - delete\n    - getMultiple\n    - setMultiple\n    - deleteMultiple\n    - clear\n    - clearExpiredItems `(Non-PSR-16)`\n- Build Data Schema\n    - MySQL\n    - SQLite\n- Garbage Collection\n- Author\n- License\n\n---\n\n## Install\n\n```bash\ncomposer require shieldon/simple-cache\n```\n\n## Usage\n\n### `Cache`\n\nClass `Cache` is an adapter that not only allows the implemented instance of `Psr\\SimpleCache\\CacheInterface`, but also has built-in drivers already.\n\n####  __construct(`$driver = ''`, `$config = []`)\n\nCreate a cache handler using the file driver.\n\nExample:\n\n```php\n$driver = new \\Shieldon\\SimpleCache\\Cache('file', [\n    'storage' =\u003e __DIR__ . '/../tmp'\n]);\n```\n\n#### `$driver`\n\n(string|CacheInterface)\n\nThe class name of a built-in driver, or a PSR-16 driver that implements `Psr\\SimpleCache\\CacheInterface`.\n\n#### `$config`\n\n(array)\n\nAn array of parameters will be passed to a built-in driver.\n\nExample:\n\n*Redis*\n```php\n$config = [\n    'host' =\u003e '127.0.0.1',\n    'port' =\u003e 6379,\n    'user' =\u003e null,\n    'pass' =\u003e null,\n];\n```\n\n*File*\n```php\n$config = [\n    'storage' =\u003e '/tmp/simple-cache',\n];\n```\n\n*Mysql*\n```php\n$config = [\n    'host'    =\u003e '127.0.0.1',\n    'port'    =\u003e 3306,\n    'user'    =\u003e null,\n    'pass'    =\u003e null,\n    'dbname'  =\u003e null,\n    'table'   =\u003e 'cache_data',\n    'charset' =\u003e 'utf8'\n];\n```\n\n*Sqlite*\n```php\n$config = [\n    'storage' =\u003e '/tmp/simple-cache',\n];\n```\n\n*Mongo*\n```php\n$config = [\n    'host'       =\u003e '127.0.0.1',\n    'port'       =\u003e 27017,\n    'user'       =\u003e null,\n    'pass'       =\u003e null,\n    'database'   =\u003e 'test',\n    'collection' =\u003e 'cache_data',\n];\n```\n\n*Memcache*, *Memcached*\n```php\n$config = [\n    'host' =\u003e '127.0.0.1',\n    'port' =\u003e 11211,\n];\n```\n\n---\n\n## API\n\nThose 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.\n\n- set\n- get\n- has\n- delete\n- setMultiple\n- getMultiple\n- deleteMultiple\n- clear\n- clearExpiredItems *(Non-PSR-16)*\n\n### set\n\n```php\npublic function set(string $key, mixed value, $ttl = null);\n```\n\nNote that **$ttl** accepts `null`,`int`,`DateInterval`.\nThe `null` means that the key never expires until deleted.\n\nExample:\n\n```php\n$cache-\u003eset('foo', 'bar', 300);\n$cache-\u003eset('foo2', 'bar2');\n\n$array = [\n    'hello' =\u003e 'world',\n    'yes' =\u003e 'Taiwan',\n];\n\n$cache-\u003eset('foo3', $array);\n$cache-\u003eset('foo4', $array, 300);\n```\n\n### get\n\n```php\npublic function get(string $key, mixed $default = null): mixed\n```\n\nExample:\n\n```php\necho $cache-\u003eget('foo', 'placeholder');\n// bar\n\nsleep(301);\n\necho $cache-\u003eget('foo', 'placeholder');\n// placeholder\n\necho $cache-\u003eget('foo');\n// null\n\necho $cache-\u003eget('foo2', 'placeholder');\n// bar2\n\n$example = $cache-\u003eget('foo3', 'placeholder');\nvar_dump($example);\n// string(11) \"placeholder\"\n\n$example = $cache-\u003eget('foo4', 'placeholder');\nvar_dump($example);\n/* \n    array(2) {\n    [\"hello\"]=\u003e\n    string(5) \"world\"\n    [\"yes\"]=\u003e\n    string(6) \"Taiwan\"\n    }\n*/\n```\n\n### has\n\n```php\npublic function has(string $key): bool\n```\n\nExample:\n\n```php\nif ($cache-\u003ehas('foo3')) {\n    echo 'foo3 exists.';\n} else {\n    echo 'foo3 does not exist.';\n}\n// foo3 exists.\n```\n\n### delete\n\n```php\npublic function delete(string $key): bool\n```\n\nExample:\n\n```php\n\nif ($cache-\u003edelete('foo3')) {\n    echo 'foo3 has been deleted successfully.';\n} else {\n    echo 'Failed to delete key foo3.';\n}\n// foo3 has been deleted successfully.\n\nif ($cache-\u003ehas('foo3')) {\n    echo 'foo3 exists.';\n} else {\n    echo 'foo3 does not exist.';\n}\n// foo3 does not exist.\n```\n\n### setMultiple\n\n```php\npublic function setMultiple(iterable $values, $ttl = null): bool\n```\n\nNote that **$ttl** accepts `null`,`int`,`DateInterval`.\nThe `null` means that the key never expires until deleted.\n\nExample:\n\n```php\n$array = [\n    'bar' =\u003e 'foo',\n    'bar2' =\u003e 'foo2',\n];\n\n$cache-\u003esetMultiple($array, 300);\n```\n\n### getMultiple\n\n```php\npublic function getMultiple(array $keys, mixed $default = null): iterable\n```\n\nExample:\n\n```php\n$example = $cache-\u003egetMultiple(['bar', 'bar2', 'bar3'], 'hello');\nvar_dump($example);\n/* \n    array(3) {\n    [\"bar\"]=\u003e\n    string(3) \"foo\"\n    [\"bar2\"]=\u003e\n    string(4) \"foo2\"\n    [\"bar3\"]=\u003e\n    string(5) \"hello\"\n    }\n*/\n```\n\n### deleteMultiple\n\n```php\npublic function deleteMultiple(array $keys): bool\n```\n\nExample:\n\n```php\nif ($cache-\u003edeleteMultiple(['bar', 'bar2'])) {\n    echo 'bar and bar2 have been deleted successfully.';\n} else {\n    echo 'Failed to delete keys bar or bar2.';\n}\n// bar and bar2 have been deleted successfully.\n\n$example = $cache-\u003egetMultiple(['bar', 'bar2', 'bar3'], 'hello');\nvar_dump($example);\n/* \n    array(3) {\n    [\"bar\"]=\u003e\n    string(5) \"hello\"\n    [\"bar2\"]=\u003e\n    string(5) \"hello\"\n    [\"bar3\"]=\u003e\n    string(5) \"hello\"\n    }\n*/\n```\n\n### clear\n\n```php\npublic function clear(): bool\n```\n\nExample:\n\n```php\nif ($cache-\u003eclear()) {\n    echo 'All cached data has been deleted successfully.';\n} else {\n    echo 'Failed to delete the cached data.';\n}\n// All cached data has been deleted successfully.\n```\n\n### clearExpiredItems `Non-PSR-16`\n\n```php\npublic function clearExpiredItems(): array\n```\n\nThis method returns a list of deleted cache keys.\n\n*Note*: **Redis** and **Memcache**, **Memcached** drivers will always return an empty array. See *Garbage Collection* section below.\n\nExample:\n\n```php\n$cache-\u003eset('foo', 'bar', 300);\n$cache-\u003eset('foo2', 'bar2', 5);\n$cache-\u003eset('foo3', 'bar3', 5);\n\nsleep(6);\n\n$expiredItems = $cache-\u003eclearExpiredItems();\nvar_dump($expiredItems);\n\n/* \n    array(2) {\n    [0]=\u003e\n    string(4) \"foo2\"\n    [1]=\u003e\n    string(4) \"foo3\"\n    }\n*/\n```\n\n---\n\n## Build Data Schema\n\nThe data schema needs to be built for the initial use of MySQL and SQLite drivers.\n\nThis API can be utilized for this purpose.\n\n```php\n$cache-\u003erebuild();\n```\n\nOr build it manually.\n\n### MySQL\n\n```sql\nCREATE TABLE IF NOT EXISTS `cache_data` (\n    `cache_key` varchar(40) NOT NULL,\n    `cache_value` longtext,\n    PRIMARY KEY (`cache_key`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;\n```\n\n### SQLite\n\n```sql\nCREATE TABLE IF NOT EXISTS cache_data (\n    cache_key VARCHAR(40) PRIMARY KEY,\n    cache_value LONGTEXT\n);\n```\n\n---\n\n## Garbage Collection\n\nFor built-in drivers, enabling garbage collection will automatically clear expired cache from your system.\n\nUse the following parameters:\n\n```php\n$config = [\n    'gc_enable'      =\u003e true,\n    'gc_divisor'     =\u003e 100, // default\n    'gc_probability' =\u003e 1, // default\n];\n```\n\nThis implies a 1% probability of executing garbage collection.\nAvoid setting it to 100% as it will unnecessarily fetch and check all keys one by one.\n\n\nExample:\n```php\n$driver = new \\Shieldon\\SimpleCache\\Cache('file', [\n    'storage'   =\u003e __DIR__ . '/../tmp',\n    'gc_enable' =\u003e true,\n]);\n```\n\nYou can just use the `gc_enable` to enable garbage collection.\n\n### Note\n\nFor the **Redis**, **Memcache**, and **Memcached** drivers, this method isn't necessary as expired items are automatically cleared.\n\n---\n\n##  Contributing\n\nThank 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:\n\n### Guidelines\n\n- Fork the repository and create your branch from master.\n- Make sure your code follows our coding style and conventions.\n- Keep your code concise, well-documented, and modular.\n- Write clear commit messages that describe the purpose of your changes.\n- Test your changes thoroughly to ensure they don't introduce any new issues.\n- Make sure your code builds successfully without any errors or warnings.\n- Update relevant documentation, including README files if necessary.\n- Submit a pull request (PR) to the master branch of the original repository.\n\n### Code Testing\n\nWe 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:\n\n- Redis\n- MongoDB\n- MySQL\n- PHP\n- Memcached\n- APCu\n\nFollow the steps below to run the tests:\n\n- Make sure you have Docker installed on your machine. If not, you can download and install it from the official Docker website.\n- Navigate to the project directory and build the Docker image by running the following command:\n    ```\n    composer test:docker:build\n    ```\n- Once the Docker image is built, you can run the tests by executing the following command:\n    ```\n    composer test:docker:run\n    ```\n- Observe the test results and make note of any failures or errors. The output will be displayed in the terminal.\n\n---\n\n## Author\n\n- [Terry L.](https://terryl.in/) and contributers, such as [Jimmy](https://colocal.com) and others.\n\n#### The Origin of this Library\n\nThis 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.\n\n## License\n\nMIT\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fterrylinooo%2Fsimple-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fterrylinooo%2Fsimple-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fterrylinooo%2Fsimple-cache/lists"}