{"id":15693996,"url":"https://github.com/nilportugues/php-cache","last_synced_at":"2025-08-20T11:04:44.126Z","repository":{"id":29260401,"uuid":"32793013","full_name":"nilportugues/php-cache","owner":"nilportugues","description":"Cache layer for PHP applications capable of being used standalone or with the Chain of Responsability pattern.","archived":false,"fork":false,"pushed_at":"2016-03-06T10:13:52.000Z","size":159,"stargazers_count":7,"open_issues_count":1,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-08T05:58:16.364Z","etag":null,"topics":["cache","cacheadapter","chain","elasticsearch","fallback","memcached","mysql","performance","php","php7","redis","standalone"],"latest_commit_sha":null,"homepage":"http://nilportugues.com","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"elastic/elasticsearch-mapper-attachments","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nilportugues.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}},"created_at":"2015-03-24T10:56:00.000Z","updated_at":"2022-02-12T14:01:38.000Z","dependencies_parsed_at":"2022-09-06T14:52:11.967Z","dependency_job_id":null,"html_url":"https://github.com/nilportugues/php-cache","commit_stats":null,"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-cache","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-cache/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-cache/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nilportugues%2Fphp-cache/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nilportugues","download_url":"https://codeload.github.com/nilportugues/php-cache/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253009892,"owners_count":21839714,"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","cacheadapter","chain","elasticsearch","fallback","memcached","mysql","performance","php","php7","redis","standalone"],"created_at":"2024-10-03T18:50:59.883Z","updated_at":"2025-05-08T05:58:22.563Z","avatar_url":"https://github.com/nilportugues.png","language":"PHP","readme":" Cache layer\n=========================\n\n[![Build Status](https://travis-ci.org/nilportugues/php-cache.svg)](https://travis-ci.org/nilportugues/php-cache) [![Coverage Status](https://coveralls.io/repos/nilportugues/cache/badge.svg?branch=master)](https://coveralls.io/r/nilportugues/cache?branch=master) [![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/nilportugues/cache/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/nilportugues/cache/?branch=master) [![SensioLabsInsight](https://insight.sensiolabs.com/projects/918cfa6d-997d-4e41-bdcb-d01970485074/mini.png)](https://insight.sensiolabs.com/projects/918cfa6d-997d-4e41-bdcb-d01970485074) [![Latest Stable Version](https://poser.pugx.org/nilportugues/cache/v/stable)](https://packagist.org/packages/nilportugues/cache) [![Total Downloads](https://poser.pugx.org/nilportugues/cache/downloads)](https://packagist.org/packages/nilportugues/cache) [![License](https://poser.pugx.org/nilportugues/cache/license)](https://packagist.org/packages/nilportugues/cache) \n[![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://paypal.me/nilportugues)\n \nCache layer for PHP applications capable of being used standalone or with the Chain of Responsability pattern.\n\n\n\n## 1. Installation\n\nThe recommended way to install this package is through [Composer](http://getcomposer.org). Run the following command to install it:\n\n```sh\nphp composer.phar require nilportugues/cache\n```\n---\n\n## 2. Features\n\n- One cache class, many adapters.\n- All cache adapters can be used as standalone cache classes.\n- Opt-in to be used as a chain of caches.\n- Implementation normalizes all mechanisms and behaviours.\n- Configuration files for all adapters in vanilla PHP and Symfony2 format provided in `config`and `migrations` directories.\n- High quality, 100% tested code.\n\n---\n\n## 3. Drivers Available\nThe package provides several implementations for a key-value cache. \n\nThe most sensitive choice is to make use of the Cache based adapters such as Redis and Memcached, which are the most performant and specialized.\n\nYet sometimes these are not available and other options should be considered, but we got you covered.\n\n### Cache based: \n- **Memcached:** MemcachedAdapter *(php5-memcached)*\n- **Redis:** RedisAdapter *(php5-redis)*, PredisAdapter *(Predis)*\n\n### Full-text based:\n- **SphinxQL:** SphinxAdapter\n- **ElasticSearch:** ElasticSearchAdapter\n\n### System based:\n- **Memory:** InMemoryAdapter\n- **FileSystem:** FileSystemAdapter\n\n### Database based:\n- **MySQL:** MySqlAdapter\n- **PostgreSql:** PostgreSqlAdapter\n- **Sqlite:** SqliteAdapter\n\n---\n## 4. Cache and CacheAdapter Interfaces\n\nThese are all the public methods available for the Cache and all of its available adapters:\n\n - **get($key)**: Get a value identified by $key.\n - **set($key, $value, $ttl = 0)**: Set a value identified by $key and with an optional $ttl.\n - **defaultTtl($ttl)**: Allows to set a default ttl value if none is provided for set()\n - **delete($key)**: Delete a value identified by $key.\n - **isAvailable()**: Checks the availability of the cache service.\n - **isHit()**: Check if value was found in the cache or not.\n - **clear()**: Clears all expired values from cache.\n - **drop()**:  Clears all values from the cache.\n\n### 4.1 - CacheAdapter\nAllows all of the public methods defined in Cache Interface.\n\nEach CacheAdapter will have a custom constructor method due to its needs, but **last parameter is always a chainable value, being another CacheAdapter.**\n\n---\n\n## 5. Example\n\n    The more cache levels the slower the cache system will be, so leverage the \n    cache to your needs. \n    Maybe you don't need a fallback mechanism at all! This is just an example.\n\n**1st level cache**\nRedis (PredisAdapter) is our main cache, in a dedicated server.\n\n**2nd level cache**\nMemcached (MemcachedAdapter) as fallback mechanism, available in the same machine as our PHP script.\n\n**Application cache**\nInMemoryAdapter, used to avoid hiting the external caches on repeated operations and is shared by all cache layers. This comes enabled by default so you don't need to worry at all.\n\n\n#### 5.1. Configuration\n\nUsing a Service Container, such as an array returning the services or a more popular solution such as Symfony's Service Container, build the caches.\n\nFor this example, we'll be building two caches, **user_cache** and **image_cache**. Both use Predis as first level cache and a fallback to Memcached if Predis cannot establish a connection during runtime.\n\n```php\n\u003c?php\ninclude_once realpath(dirname(__FILE__)).'/vendor/autoload.php';\n\nuse NilPortugues\\Cache\\Adapter\\MemcachedAdapter;\nuse NilPortugues\\Cache\\Adapter\\PredisAdapter;\nuse NilPortugues\\Cache\\Cache;\n\n$parameters = include_once realpath(dirname(__FILE__)).'/cache_parameters.php';\n\n$cache = new PredisAdapter(\n    $parameters['redis'],\n    //here we're chaining the $memcachedAdapter\n    new MemcachedAdapter(\n        $parameters['memcached']['persistent_id'],\n        $parameters['memcached']['connections']\n    );\n);\n\nreturn [\n    'user_cache' =\u003e new Cache($cache, 'user', 60*5), //5 minutes cache\n    'image_cache' =\u003e new Cache($cache, 'image', 60*60), //1 hour cache\n];\n```\n\n### 5.2. Usage\n\nNow, using a Service Container, we'll get the **user_cache** to fetch data, or add if it does not exist. This data will be stored in the caches. \n\nFor fetching, first it's checked if data is available in memory, if not, it's fetched from the data storage, added to the in memory cache and returned to the user.\n\n```php\n$db = $this-\u003eserviceContainer-\u003eget('database');\n$cache = $this-\u003eserviceContainer-\u003eget('cache');\n\n$userId = 1;\n$cacheKey = sprintf(\"user:id:%s\", $userId);\n\n$user = $cache-\u003eget($cacheKey);\nif(null !== $user) {\n  return $user;\n}\n\n$user = $db-\u003efindById($userId);\n$cache-\u003eset($cacheKey, $user);\n\nreturn $user;\n```\n\n And that's pretty much it. Notice how same key is used for the get and set methods.\n\n\n### 5.3 Other configurations\n\n#### 5.3.1 ElasticSearch as cache\n\nIt is important that you configure your ElasticSearch by appending the following line to the **elasticsearch.yml** file:\n\n```yml\nindices.ttl.interval: 1s\n```\n\nNow restart the ElasticSearch daemon.\n\nIf you're wondering where the cache index definition is, the creation of index is handled by the adapter on instantiation if it does not already exist.\n\n#### 5.3.2 Sphinx as cache\nConfiguration provided in the `/migrations/sphinx.conf` file.\n\n#### 5.3.3 MySQL as cache\nConfiguration provided in the `/migrations/mysql_schema.sql` file.\n\n#### 5.3.4 Postgres as cache\nConfiguration provided in the `/migrations/postgresql_schema.sql` file.\n\n#### 5.3.5 Sqlite as cache\nConfiguration provided in the `/migrations/sqlite_schema.sqlite` file.\n\n\n---\n\n\n## 6. Quality\n\nTo run the PHPUnit tests at the command line, go to the tests directory and issue phpunit.\n\nThis library attempts to comply with PSR-1, PSR-2, and PSR-4. If you notice compliance oversights, please send a patch via pull request.\n\n\n---\n\n\n## 7. Author\nNil Portugués Calderó\n\n - \u003ccontact@nilportugues.com\u003e\n - [http://nilportugues.com](http://nilportugues.com)\n\n\n---\n\n\n## 8. License\nThe code base is licensed under the MIT license.\n\n","funding_links":["https://paypal.me/nilportugues"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fphp-cache","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnilportugues%2Fphp-cache","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnilportugues%2Fphp-cache/lists"}