{"id":22764605,"url":"https://github.com/kuria/cache","last_synced_at":"2026-02-14T04:07:13.914Z","repository":{"id":57009925,"uuid":"21081515","full_name":"kuria/cache","owner":"kuria","description":"Caching library with driver abstraction","archived":false,"fork":false,"pushed_at":"2023-04-22T14:38:40.000Z","size":217,"stargazers_count":2,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-24T01:35:42.633Z","etag":null,"topics":["apcu","cache","caching","file","filesystem","memcached","php","psr-16","psr-6","redis","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/kuria.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGELOG.rst","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,"publiccode":null,"codemeta":null}},"created_at":"2014-06-21T23:58:14.000Z","updated_at":"2023-09-19T17:45:38.000Z","dependencies_parsed_at":"2024-12-11T12:19:35.752Z","dependency_job_id":null,"html_url":"https://github.com/kuria/cache","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"purl":"pkg:github/kuria/cache","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kuria%2Fcache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kuria%2Fcache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kuria%2Fcache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kuria%2Fcache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/kuria","download_url":"https://codeload.github.com/kuria/cache/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/kuria%2Fcache/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29435556,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-14T03:34:37.767Z","status":"ssl_error","status_checked_at":"2026-02-14T03:34:09.092Z","response_time":53,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"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":["apcu","cache","caching","file","filesystem","memcached","php","psr-16","psr-6","redis","simple-cache"],"created_at":"2024-12-11T12:09:28.581Z","updated_at":"2026-02-14T04:07:13.886Z","avatar_url":"https://github.com/kuria.png","language":"PHP","readme":"Cache\n#####\n\nCaching library with driver abstraction.\n\n.. image:: https://travis-ci.com/kuria/cache.svg?branch=master\n   :target: https://travis-ci.com/kuria/cache\n\n.. contents::\n   :depth: 3\n\n\nFeatures\n********\n\n- entry operations: has, add, set, get, delete\n- multiple-entry operations: getting, setting, adding, deleting\n- listing, filtering, cleanup (requires driver support)\n- TTL expiration\n- key prefixing / namespacing\n- stored and retrieved values can be manipulated via events\n- `PSR-6 \u003chttp://www.php-fig.org/psr/psr-6/\u003e`_ cache adapter\n- `PSR-16 \u003chttp://www.php-fig.org/psr/psr-16/\u003e`_ simple cache wrapper\n- multiple built-in driver implementations\n\n\nRequirements\n************\n\n- PHP 7.1+\n\n\nBuilt-in drivers\n****************\n\n==================== ========== =========== ============ ========== ============== ==========================================================\nDriver               Multi-read Multi-write Multi-delete Filterable Manual cleanup Required extension\n==================== ========== =========== ============ ========== ============== ==========================================================\n``FilesystemDriver`` no         no          no           yes        yes            none\n``ApcuDriver``       yes        yes         yes          yes        no             `APCu \u003chttp://php.net/manual/en/book.apcu.php\u003e`_\n``MemcachedDriver``  yes        partial     yes          no         no             `Memcached \u003chttp://php.net/manual/en/book.memcached.php\u003e`_\n``RedisDriver``      yes        yes         yes          yes        no             `PhpRedis \u003chttps://github.com/phpredis/phpredis\u003e`_\n``MemoryDriver``     yes        yes         yes          yes        yes            none\n``BlackHoleDriver``  no         no          no           yes        no             none\n==================== ========== =========== ============ ========== ============== ==========================================================\n\n.. NOTE::\n\n   The cache will emulate multi-read/write/delete if the driver doesn't support it natively.\n\n\nUsage\n*****\n\nCreating a cache instance\n=========================\n\nFilesystem\n----------\n\nStore cache entries in the given directory as binary files.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Cache;\n   use Kuria\\Cache\\Driver\\Filesystem\\FilesystemDriver;\n\n   $driver = new FilesystemDriver(__DIR__ . '/cache');\n   $cache = new Cache($driver);\n\n.. NOTE::\n\n   If needed, ``$cache-\u003ecleanup()`` may to be called to physically remove expired\n   entries from the filesystem. This is best done periodically via CRON or a similar\n   mechanism.\n\n\nStoring cache entries as PHP files\n^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n\nIt may be beneficial to store cache entries as actual PHP files (instead of binary ones),\nso that they may be picked up by opcode caches (e.g. `opcache \u003chttp://php.net/manual/en/book.opcache.php\u003e`_)\nto increase performance.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Cache;\n   use Kuria\\Cache\\Driver\\Filesystem\\Entry\\File\\PhpFileFormat;\n   use Kuria\\Cache\\Driver\\Filesystem\\FilesystemDriver;\n\n   $driver = new FilesystemDriver(\n       __DIR__ . '/cache',\n       FilesystemDriver::createEntryFactory(new PhpFileFormat())\n   );\n\n   $cache = new Cache($driver);\n\n.. TIP::\n\n   When caching large amounts of data this way, make sure the opcode cache\n   is configured appropriately.\n\n   For *opcache*, the most relevant settings are ``opcache.memory_consumption``\n   and ``opcache.max_accelerated_files``.\n\n.. WARNING::\n\n   To take full advantage of opcode caching, ``PhpFileFormat`` uses ``var_export()``\n   instead of ``serialize()``. Objects can be stored in the cache only if they\n   implement the `__set_state() \u003chttp://php.net/manual/en/language.oop5.magic.php#object.set-state\u003e`_\n   method.\n\n\nAPCu\n----\n\nStore cache entries using `APCu \u003chttp://php.net/manual/en/book.apcu.php\u003e`_.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Cache;\n   use Kuria\\Cache\\Driver\\Apcu\\ApcuDriver;\n\n   $cache = new Cache(new ApcuDriver());\n\n\nMemcached\n---------\n\nStore cache entries using `Memcached \u003chttp://php.net/manual/en/book.memcached.php\u003e`_.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Cache;\n   use Kuria\\Cache\\Driver\\Memcached\\MemcachedDriver;\n\n   $memcached = new \\Memcached();\n   $memcached-\u003eaddServer('localhost', 11211);\n\n   $cache = new Cache(new MemcachedDriver($memcached));\n\n\nRedis\n-----\n\nStore cache entries using `PhpRedis \u003chttps://github.com/phpredis/phpredis\u003e`_.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Cache;\n   use Kuria\\Cache\\Driver\\Redis\\RedisDriver;\n\n   $redis = new \\Redis();\n   $redis-\u003econnect('localhost', 6380); // might return FALSE..\n\n   $cache = new Cache(new RedisDriver($redis));\n\n\nMemory\n------\n\nStore cache entries in memory.\n\nThese entries are only available for the duration of the script\nand aren't shared between threads.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Cache;\n   use Kuria\\Cache\\Driver\\Memory\\MemoryDriver;\n\n   $cache = new Cache(new MemoryDriver());\n\n.. NOTE::\n\n   Expired entries aren't purged from memory until an attempt to access them\n   is made. ``$cache-\u003ecleanup()`` may be called to purge all expired entries\n   immediately.\n\n\nBlack hole\n----------\n\nStored entries are discarded immediately. Useful for testing or debugging.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Cache;\n   use Kuria\\Cache\\Driver\\BlackHole\\BlackHoleDriver;\n\n   $cache = new Cache(new BlackHoleDriver());\n\n\nCache methods\n=============\n\n\n``setPrefix()`` - configure cache prefix\n----------------------------------------\n\nThe ``setPefix()`` method defines a prefix that will be applied to all keys before\nthey are passed to the underlying driver implementation.\n\nThe prefix can be an empty string to disable this functionality.\n\n.. code:: php\n\n   \u003c?php\n\n   $cache-\u003esetPrefix('prefix_');\n\n\n``getNamespace()`` - get a namespaced cache instance\n----------------------------------------------------\n\nThe ``getNamespace()`` method returns a cache instance that applies a prefix to all\nkeys before passing them to the original cache.\n\n.. code:: php\n\n   \u003c?php\n\n   $fooCache = $cache-\u003egetNamespace('foo.');\n\n   $fooCache-\u003eget('bar'); // reads foo.bar\n   $fooCache-\u003edelete('baz'); // deletes foo.baz\n   $fooCache-\u003eclear(); // deletes foo.* (if the cache is filterable)\n   // etc.\n\n\n``has()`` - check if an entry exists\n------------------------------------\n\nThe ``has()`` method returns ``TRUE`` or ``FALSE`` indicating whether the\nentry exists or not.\n\n.. code:: php\n\n   \u003c?php\n\n   if ($cache-\u003ehas('key')) {\n       echo 'Entry exist';\n   } else {\n       echo 'Entry does not exist';\n   }\n\n.. WARNING::\n\n   Beware of a possible race-condition between calls to ``has()`` and ``get()``.\n\n   If possible, only call ``get()`` and check for a ``NULL`` result or use its\n   ``$exists`` argument.\n\n\n``get()`` - read a single entry\n-------------------------------\n\nThe ``get()`` method returns the stored value or ``NULL`` if the entry does not exist.\n\n.. code:: php\n\n   \u003c?php\n\n   $value = $cache-\u003eget('key');\n\nIf you need to distinguish between a ``NULL`` value and a nonexistent entry, use\nthe ``$exists`` argument:\n\n.. code:: php\n\n   \u003c?php\n\n   $value = $cache-\u003eget('key', $exists);\n\n   if ($exists) {\n       // entry was found\n       // $value might be NULL if NULL was stored\n   } else {\n       // entry was not found\n   }\n\n\n``getMultiple()`` - read multiple entries\n-----------------------------------------\n\nThe ``getMultiple()`` method returns a key-value map. Nonexistent keys will have\na ``NULL`` value.\n\n.. code:: php\n\n   \u003c?php\n\n   $values = $cache-\u003egetMultiple(['foo', 'bar', 'baz']);\n\nIf you need to distinguish between ``NULL`` values and a nonexistent entries, use\nthe ``$failedKeys`` argument:\n\n.. code:: php\n\n   \u003c?php\n\n   $values = $cache-\u003egetMultiple(['foo', 'bar', 'baz'], $failedKeys);\n\n   // $failedKeys will contain a list of keys that were not found\n\n\n``listKeys()`` - list keys in the cache\n---------------------------------------\n\nThe ``listKeys()`` method will return an iterable list of keys in the cache, optionally\nmatching a common prefix.\n\nIf the driver doesn't support this operation, an ``UnsupportedOperationException``\nexception will be thrown. You can check support using the ``isFilterable()`` method.\n\n.. code:: php\n\n   \u003c?php\n\n   if ($cache-\u003eisFilterable()) {\n       // list all keys\n       foreach ($cache-\u003elistKeys() as $key) {\n           echo \"{$key}\\n\";\n       }\n\n       // list keys beginning with foo_\n       foreach ($cache-\u003elistKeys('foo_') as $key) {\n           echo \"{$key}\\n\";\n       }\n   }\n\n\n``getIterator()`` - list keys and values in the cache\n-----------------------------------------------------\n\nThe ``getIterator()`` method will return an iterator for all keys and values in the\ncache. This is a part of the ``IteratorAggregate`` interface.\n\nIf the driver doesn't support this operation, an ``UnsupportedOperationException``\nexception will be thrown. You can check support using the ``isFilterable()`` method.\n\nListing all keys and values:\n\n.. code:: php\n\n   \u003c?php\n\n   foreach ($cache as $key =\u003e $value) {\n       echo $key, ': ';\n       var_dump($value);\n   }\n\nListing keys and values matching a prefix:\n\n.. code:: php\n\n   \u003c?php\n\n   foreach ($cache-\u003egetIterator('foo_') as $key =\u003e $value) {\n       echo $key, ': ';\n       var_dump($value);\n   }\n\n\n``add()`` / ``set()`` - create a new entry\n------------------------------------------\n\nThe ``add()`` and ``set()`` methods both create an entry in the cache.\n\nThe ``set()`` method will overwrite an existing entry, but ``add()`` will not.\n\nSee `Allowed value types`_.\n\n.. code:: php\n\n   \u003c?php\n\n   $cache-\u003eadd('foo', 'foo-value');\n\n   $cache-\u003eset('bar', 'bar-value');\n\nTTL (time-to-live in seconds) can be specified using the third argument:\n\n.. code:: php\n\n   \u003c?php\n\n   $cache-\u003eset('foo', 'foo-value', 60);\n\n   $cache-\u003eadd('bar', 'bar-value', 120);\n\nIf TTL is ``NULL``, ``0`` or negative, the entry will not have an expiration time.\n\n\n``addMultiple()`` / ``setMultiple()`` - create multiple entries\n---------------------------------------------------------------\n\nThe ``addMultiple()`` and ``setMultiple()`` methods both create multiple entries\nin the cache.\n\nThe ``setMultiple()`` method will overwrite any existing entries with the same keys,\nbut ``addMultiple()`` will not.\n\nSee `Allowed value types`_.\n\n.. code:: php\n\n   \u003c?php\n\n   $cache-\u003eaddMultiple(['foo' =\u003e 'foo-value', 'bar' =\u003e 'bar-value']);\n\n   $cache-\u003esetMultiple(['foo' =\u003e 'foo-value', 'bar' =\u003e 'bar-value']);\n\nTTL (time-to-live in seconds) can be specified using the second argument:\n\n.. code:: php\n\n   \u003c?php\n\n   $cache-\u003eaddMultiple(['foo' =\u003e 'foo-value', 'bar' =\u003e 'bar-value'], 60);\n\n   $cache-\u003esetMultiple(['foo' =\u003e 'foo-value', 'bar' =\u003e 'bar-value'], 120);\n\nIf TTL is ``NULL``, ``0`` or negative, the entries will not have expiration times.\n\n\n``cached()`` - cache the result of a callback\n---------------------------------------------\n\nThe ``cached()`` method tries to read a value from the cache. If it does not exist,\nit invokes the given callback and caches its return value (even if it is ``NULL``).\n\n.. code:: php\n\n   \u003c?php\n\n   $value = $cache-\u003ecached('key', 60, function () {\n       // some expensive operation\n       $result = 123;\n\n       return $result;\n   });\n\n\n``delete()`` - delete an entry\n------------------------------\n\nThe ``delete()`` method deletes a single entry from the cache.\n\n.. code:: php\n\n   \u003c?php\n\n   if ($cache-\u003edelete('key')) {\n       echo 'Entry deleted';\n   }\n\n\n``deleteMultiple()`` - delete multiple entries\n----------------------------------------------\n\nThe ``deleteMultiple()`` method deletes multiple entries from the cache.\n\n.. code:: php\n\n   \u003c?php\n\n   if ($cache-\u003edeleteMultiple(['foo', 'bar', 'baz'])) {\n       echo 'All entries deleted';\n   } else {\n       echo 'One or more entries could not be deleted';\n   }\n\n\n``filter()`` - delete entries using a prefix\n--------------------------------------------\n\nThe ``filter()`` method deletes all entries that match the given prefix.\n\nIf the driver doesn't support this operation, an ``UnsupportedOperationException``\nexception will be thrown. You can check support using the ``isFilterable()`` method.\n\n.. code:: php\n\n   \u003c?php\n\n   if ($cache-\u003eisFilterable()) {\n       $cache-\u003efilter('foo_');\n   }\n\n\n``clear()`` - delete all entries\n--------------------------------\n\nThe ``clear()`` method deletes all entries.\n\nIf a cache prefix is set and the cache is filterable, only entries matching\nthat prefix will be cleared.\n\n.. code:: php\n\n   \u003c?php\n\n   $cache-\u003eclear();\n\n\n``cleanup()`` - clean-up the cache\n----------------------------------\n\nSome cache drivers (e.g. ``FilesystemDriver``) support explicit triggering of the cleanup\nprocedures (removal of expired entries etc).\n\nIf the driver doesn't support this operation, an ``UnsupportedOperationException``\nexception will be thrown. You can check support using the ``supportsCleanup()`` method.\n\n.. code:: php\n\n   \u003c?php\n\n   if ($cache-\u003esupportsCleanup()) {\n       $cache-\u003ecleanup();\n   }\n\n\nAllowed value types\n===================\n\nAll types except for the resource type can be stored in the cache.\n\nMost drivers use standard `object serialization \u003chttp://php.net/manual/en/language.oop5.serialization.php\u003e`_.\n\n\nCache events\n============\n\n``CacheEvents::HIT``\n--------------------\n\nEmitted when an entry has been read.\n\nThe listener is passed the key and value.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\CacheEvents;\n\n   $cache-\u003eon(CacheEvents::HIT, function (string $key, $value) {\n       printf(\n           \"Read key %s from the cache, the value is %s\\n\",\n           $key,\n           var_export($value, true)\n       );\n   });\n\n\n``CacheEvents::MISS``\n---------------------\n\nEmitted when an entry has not been found.\n\nThe listener is passed the key.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\CacheEvents;\n\n   $cache-\u003eon(CacheEvents::MISS, function (string $key) {\n       echo \"The key {$key} was not found in the cache\\n\";\n   });\n\n\n``CacheEvents::WRITE``\n----------------------\n\nEmitted when an entry is about to be written.\n\nThe listener is passed the key, value, TTL and overwrite flag.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\CacheEvents;\n\n   $cache-\u003eon(CacheEvents::WRITE, function (string $key, $value, ?int $ttl, bool $overwrite) {\n       printf(\n           \"Writing key %s to the cache, with TTL = %s, overwrite = %s and value = %s\\n\",\n           $key,\n           var_export($ttl, true),\n           var_export($overwrite, true),\n           var_export($value, true)\n       );\n   });\n\n\n``CacheEvents::DRIVER_EXCEPTION``\n---------------------------------\n\nEmitted when the underlying driver implementation throws an exception.\n\nThe listener is passed the exception object. This can be used for debugging or logging\npurposes.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\CacheEvents;\n\n   $cache-\u003eon(CacheEvents::DRIVER_EXCEPTION, function (\\Throwable $e) {\n       echo 'Driver exception: ', $e;\n   });\n\n\nPSR-6: Cache adapter\n====================\n\nThe ``CacheItemPool`` class is an adapter implementing the ``Psr\\Cache\\CacheItemPoolInterface``.\n\nTo use it, you need to have ``psr/cache`` (``^1.0``) installed.\n\nSee http://www.php-fig.org/psr/psr-6/ for more information.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Psr\\CacheItemPool;\n\n   $pool = new CacheItemPool($cache);\n\nAlso see `Creating a cache instance`_.\n\n.. TIP::\n\n   Count-based auto-commit is supported. Use ``setAutoCommitCount()`` to enable it.\n\n\nPSR-16: Simple cache wrapper\n============================\n\nThe ``SimpleCache`` class is a wrapper implementing the ``Psr\\SimpleCache\\CacheInterface``.\n\nTo use it, you need to have ``psr/simple-cache`` (``^1.0``) installed.\n\nSee http://www.php-fig.org/psr/psr-16/ for more information.\n\n.. code:: php\n\n   \u003c?php\n\n   use Kuria\\Cache\\Psr\\SimpleCache;\n\n   $simpleCache = new SimpleCache($cache);\n\nAlso see `Creating a cache instance`_.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkuria%2Fcache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkuria%2Fcache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkuria%2Fcache/lists"}