{"id":19250267,"url":"https://github.com/charcoalphp/cache","last_synced_at":"2026-06-12T01:31:10.338Z","repository":{"id":37806343,"uuid":"505905609","full_name":"charcoalphp/cache","owner":"charcoalphp","description":"[READ-ONLY] Charcoal service provider for the Stash Cache Library","archived":false,"fork":false,"pushed_at":"2024-03-13T15:05:20.000Z","size":94,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-02-05T06:36:36.619Z","etag":null,"topics":["cache","charcoal","php","read-only-repository","stash"],"latest_commit_sha":null,"homepage":"https://github.com/charcoalphp/charcoal","language":"PHP","has_issues":false,"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/charcoalphp.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":"2022-06-21T15:42:37.000Z","updated_at":"2022-06-21T19:28:42.000Z","dependencies_parsed_at":"2024-01-13T04:49:45.689Z","dependency_job_id":"645375e7-988d-4289-9c6d-dd1816b70331","html_url":"https://github.com/charcoalphp/cache","commit_stats":{"total_commits":46,"total_committers":4,"mean_commits":11.5,"dds":0.4782608695652174,"last_synced_commit":"06068f3b7af409fceedd02a32b69c60902e2b312"},"previous_names":[],"tags_count":36,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/charcoalphp%2Fcache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/charcoalphp%2Fcache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/charcoalphp%2Fcache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/charcoalphp%2Fcache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/charcoalphp","download_url":"https://codeload.github.com/charcoalphp/cache/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":240342819,"owners_count":19786584,"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":["cache","charcoal","php","read-only-repository","stash"],"created_at":"2024-11-09T18:16:40.607Z","updated_at":"2026-06-12T01:31:10.324Z","avatar_url":"https://github.com/charcoalphp.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"Charcoal Cache\n==============\n\nThe Cache package provides an integration with [Stash] for caching the results of expensive tasks.\n\n## Installation\n\n```shell\ncomposer require charcoal/cache\n```\n\nFor Charcoal projects, the service provider can be registered from your configuration file:\n\n```json\n{\n    \"service_providers\": {\n        \"charcoal/cache/service-provider/cache\": {}\n    }\n}\n```\n\n## Overview\n\n### Service Provider\n\n#### Parameters\n\n* **cache/available-drivers**: Collection of registered cache drivers that are supported by this system (via [`Stash\\DriverList`][stash-drivers]).\n\n#### Services\n\n* **cache/config**: Configuration object for the caching service.  \n    See [Pool Configuration](#pool-configuration) for available options.\n* **cache/drivers**: Collection of cache driver instances (as a service container) which uses `cache/available-drivers`.  \n    These drivers are pre-configured:\n  * **file**: [FileSystem](https://www.stashphp.com/Drivers.html#filesystem)\n  * **db**: [SQLite](https://www.stashphp.com/Drivers.html#sqlite)\n  * **apc**: [APC](https://www.stashphp.com/Drivers.html#apc)\n  * **memcache**: [Memcached](https://www.stashphp.com/Drivers.html#memcached)\n  * **redis**: [Redis](https://www.stashphp.com/Drivers.html#redis)\n  * **memory**: [Ephemeral](https://www.stashphp.com/Drivers.html#ephemeral) (Runtime Only)\n  * **noop**: Blackhole (NULL caching driver)\n* **cache/builder**: Instance of [`CacheBuilder`][src-builder] that is used to build a cache pool.\n* **cache/driver**: Reference to the Stash cache driver used by `cache`. Defaults to \"memory\".\n* **cache**: Main instance of the Stash cache pool which uses `cache/driver` and `cache/config.prefix`.\n\n## Configuration\n\n### Pool Configuration\n\nEach pool comes with a set of default options which can be individually overridden.\n\n| Setting         | Type       | Default    | Description |\n|:----------------|:----------:|:----------:|:------------|\n| **active**      | `boolean`  | `TRUE`     | Whether to enable or disable the cache service.\n| **prefix**      | `string`   | `charcoal` | Name of the main Stash pool.\n| **types**       | `string[]` | `memory`   | List of cache drivers to choose from for the main Stash pool. Defaults to \"memory\".\n| **default_ttl** | `integer`  | 1 week     | Default time-to-live (in seconds) for a cached item. Currently, only used by the APC driver (`cache/drivers.apc`).\n\n```php\nuse Charcoal\\Cache\\CacheConfig;\nuse Charcoal\\Cache\\ServiceProvider\\CacheServiceProvider;\n\n$container-\u003eregister(new CacheServiceProvider());\n\n$container['cache/config'] = new CacheConfig([\n    'prefix' =\u003e 'foobar',\n    'types'  =\u003e [ 'apc', 'memcache', 'redis' ],\n]);\n```\n\n### Driver Configuration\n\n~~Each driver comes with a set of default options which can be individually overridden.~~\n\n—N/A—\n\n## Usage\n\nJust fetch the default cache pool service:\n\n```php\n$pool = $this-\u003econtainer-\u003eget('cache');\n```\n\nOr a custom-defined cache pool:\n\n```php\n// Create a Stash pool with the Memcached driver and a custom namespace.\n$pool1 = $this-\u003econtainer-\u003eget('cache/builder')-\u003ebuild('memcache', 'altcache');\n\n// Create a custom Stash pool with the FileSystem driver and custom features.\n$pool2 = $this-\u003econtainer-\u003eget('cache/builder')-\u003ebuild('file', [\n    'namespace'  =\u003e 'mycache',\n    'logger'     =\u003e $this-\u003econtainer-\u003eget('logger.custom_logger'),\n    'pool_class' =\u003e \\MyApp\\Cache\\Pool::class,\n    'item_class' =\u003e \\MyApp\\Cache\\Item::class,\n]);\n\n// Create a Stash pool with the \"memory\" cache driver.\n$pool3 = new \\Stash\\Pool($container['cache/drivers']['memory']);\n```\n\nThen you can use the cache service directly:\n\n```php\n// Get a Stash object from the cache pool.\n$item = $pool-\u003egetItem(\"/user/{$userId}/info\");\n\n// Get the data from it, if any happens to be there.\n$userInfo = $item-\u003eget();\n\n// Check to see if the cache missed, which could mean that it either\n// didn't exist or was stale.\nif ($item-\u003eisMiss()) {\n    // Run the relatively expensive code.\n    $userInfo = loadUserInfoFromDatabase($userId);\n\n    // Set the new value in $item.\n    $item-\u003eset($userInfo);\n\n    // Store the expensive code so the next time it doesn't miss.\n    $pool-\u003esave($item);\n}\n\nreturn $userInfo;\n```\n\nSee the [Stash documentation](stash-docs) for more information on using the cache service.\n\n### Middleware\n\nThe [`CacheMiddleware`][src-middleware] is available for PSR-7 applications that support middleware. The middleware saves the HTTP response body and headers into a [PSR-6 cache pool](psr-6) and returns that cached response if still valid.\n\nIf you are using [charcoal/app], you can add the middleware via the application configset:\n\n```json\n\"middlewares\": {\n    \"charcoal/cache/middleware/cache\": {\n        \"active\": true,\n        \"methods\": [ \"GET\", \"HEAD\" ]\n    }\n}\n```\n\nOtherwise, with [Slim](https://github.com/slimphp/slim), for example:\n\n```php\nuse Charcoal\\Cache\\Middleware\\CacheMiddleware;\nuse Slim\\App;\nuse Stash\\Pool;\n\n$app = new App();\n\n// Register middleware\n$app-\u003eadd(new CacheMiddleware([\n    'cache'   =\u003e new Pool(),\n    'methods' =\u003e [ 'GET', 'HEAD' ],\n]));\n```\n\nThe middleware comes with a set of default options which can be individually overridden.\n\n| Setting            | Type                     | Default     | Description |\n|:-------------------|:------------------------ |:-----------:|:------------|\n| **active**         | `boolean`                | `FALSE`     | Whether to enable or disable the middleware ([charcoal/app] only).\n| **cache**          | `CacheItemPoolInterface` | `cache`     | Required; The main Stash pool.\n| **ttl**            | `string[]`               | 1 week      | Time-to-live (in seconds) for a cached response.\n| **methods**        | `string[]`               | `GET`       | Accepted HTTP method(s) to cache the response.\n| **status_codes**   | `integer[]`              | 200         | Accepted HTTP status code(s) to cache the response.\n| **included_path**  | `string[]`               | `*`         | Accepted URI paths for caching the response.\n| **excluded_path**  | `string[]`               | `^/admin\\b` | Rejected URI paths for caching the response.\n| **included_query** | `string[]`               | `NULL`      | Accepted query parameters for caching the response.\n| **excluded_query** | `string[]`               | `NULL`      | Rejected query parameters for caching.\n| **ignored_query**  | `string[]`               | `NULL`      | Ignored query parameters for caching the response.\n\n#### By Default\n\nAll HTTP responses are cached unless:\n\n1.  the request method is not GET\n2.  the request URI path starts with `/admin…`\n3.  the request URI contains a query string\n4.  the response is not OK (200)\n\n#### Ignoring Query Strings\n\nIf query strings don't affect the server's response, you can permit caching of requests by ignoring all query parameters:\n\n```json\n\"ignored_query\": \"*\"\n```\n\nor some of them:\n\n```json\n\"ignored_query\": [ \"sort\", \"theme\" ]\n```\n\n### Helpers\n\n#### CachePoolAwareTrait\n\nThe [`CachePoolAwareTrait`][src-helper] is offered as a convenience to avoid duplicate / boilerplate code. It simply sets and gets an instance of `\\Psr\\Cache\\CacheItemPoolInterface`.\n\nAssign a cache pool with `setCachePool()` and retrieve it with `cachePool()`.  \n\nBoth methods are protected; this trait has no public interface.\n\n## Resources\n\n* [Contributing](https://github.com/charcoalphp/.github/blob/main/CONTRIBUTING.md)\n* [Report issues](https://github.com/charcoalphp/charcoal/issues) and\n  [send pull requests](https://github.com/charcoalphp/charcoal/pulls)\n  in the [main Charcoal repository](https://github.com/charcoalphp/charcoal)\n\n[src-middleware]: src/Charcoal/Cache/Middleware/CacheMiddleware.php\n[src-provider]:   src/Charcoal/Cache/ServiceProvider/CacheServiceProvider.php\n[src-helper]:     src/Charcoal/Cache/CachePoolAwareTrait.php\n[src-builder]:    src/Charcoal/Cache/CacheBuilder.php\n[src-config]:     src/Charcoal/Cache/CacheConfig.php\n[charcoal/app]:   https://github.com/charcoalphp/app\n[Stash]:          https://github.com/tedious/Stash\n[stash-drivers]:  https://github.com/tedious/Stash/blob/v0.14.2/src/Stash/DriverList.php\n[stash-docs]:     https://www.stashphp.com/\n[stash-license]:  https://github.com/tedious/Stash/blob/v0.14.2/LICENSE\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcharcoalphp%2Fcache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcharcoalphp%2Fcache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcharcoalphp%2Fcache/lists"}