PHPackages                             elfaruklabs/generic-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. elfaruklabs/generic-cache

ActiveLibrary[Caching](/categories/caching)

elfaruklabs/generic-cache
=========================

A lightweight file-based caching library for PHP with TTL, atomic writes, and file locking.

v1.0.0(today)01↑2900%MITPHPPHP &gt;=5.6

Since Jul 30Pushed todayCompare

[ Source](https://github.com/ElfarukLabs/GenericCache)[ Packagist](https://packagist.org/packages/elfaruklabs/generic-cache)[ Docs](https://github.com/ElfarukLabs/GenericCache)[ RSS](/packages/elfaruklabs-generic-cache/feed)WikiDiscussions main Synced today

READMEChangelogDependenciesVersions (2)Used By (0)

[![PHP](https://camo.githubusercontent.com/f7cb9c3b3584eef50dce3ec928ee88203ee61969d9c678eb49aa5cfd7d2c13ec/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344352e362d3737374242343f6c6f676f3d706870)](https://camo.githubusercontent.com/f7cb9c3b3584eef50dce3ec928ee88203ee61969d9c678eb49aa5cfd7d2c13ec/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344352e362d3737374242343f6c6f676f3d706870)[![License](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)](https://camo.githubusercontent.com/784362b26e4b3546254f1893e778ba64616e362bd6ac791991d2c9e880a3a64e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d677265656e2e737667)[![Status](https://camo.githubusercontent.com/9e968d9471725151bf93b46bcd079913754b36f39f5205ac6b0c1e18328adb7b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5374617475732d537461626c652d627269676874677265656e)](https://camo.githubusercontent.com/9e968d9471725151bf93b46bcd079913754b36f39f5205ac6b0c1e18328adb7b/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5374617475732d537461626c652d627269676874677265656e)

GenericCache
============

[](#genericcache)

A lightweight, file-based caching library for PHP with support for **TTL (Time-To-Live)**, **atomic writes**, and **file locking**.

GenericCache is designed for developers who need a reliable caching solution without requiring external services such as **Redis** or **Memcached**. It is especially useful for shared hosting environments and small to medium-sized PHP applications where deploying additional infrastructure is unnecessary or unavailable.

By combining **Cache Aside**, **Stale While Revalidate**, **file locking**, and **atomic writes**, GenericCache helps reduce database queries while ensuring cache consistency and preventing race conditions.

---

Why GenericCache?
-----------------

[](#why-genericcache)

Many PHP applications are deployed on environments where installing or managing services like Redis or Memcached is not possible.

GenericCache provides a practical alternative using only the local file system while still supporting features commonly found in modern caching solutions.

### Design Goals

[](#design-goals)

- Keep the API simple and easy to learn.
- Require no external services or extensions.
- Prevent race conditions during cache generation.
- Use atomic writes to avoid corrupted cache files.
- Support reusable integration across different projects.
- Remain lightweight and portable.

---

Features
--------

[](#features)

- File-based caching
- Configurable TTL (Time-To-Live)
- Automatic cache expiration
- Cache Aside strategy (`getOrFetch()`)
- Stale-While-Revalidate strategy (`getOrFetchStale()`)
- File locking using `flock()`
- Atomic file writes
- Cache hit and miss statistics
- Recursive cleanup of expired cache files
- Generic design suitable for any type of JSON-serializable data

---

Requirements
------------

[](#requirements)

- PHP 5.6 or later
- Writable cache directory

---

Security Considerations
-----------------------

[](#security-considerations)

GenericCache stores cache entries as files. Ensure that your cache directory is not publicly accessible through your web server.

Whenever possible, place the cache directory outside the public web root.

Example:

```
public/
└── index.php

storage/
└── cache/

```

The application should access cache data through GenericCache methods instead of allowing direct file access.

If the cache directory must be located inside a public directory, configure your web server to block direct access.

For Apache, you can use an `.htaccess` file inside the cache directory:

```

    Require all denied

```

Why?

Cache entries may contain application data stored by your application, such as database results, API responses, or user-related information.

A user should never be able to access cache files directly through a URL such as:

```
https://example.com/cache/users/item_1.json

```

Proper cache directory placement and web server configuration help prevent accidental exposure of cached data.

---

Installation
------------

[](#installation)

### Composer

[](#composer)

```
composer require elfaruklabs/generic-cache
```

Install the package and include Composer's autoloader:

```
require 'vendor/autoload.php';

use ElfarukLabs\Cache\GenericCache;
```

### Manual Installation

[](#manual-installation)

Clone or download this repository and include the library in your project.

```
require_once __DIR__ . '/src/GenericCache.php';
```

---

Quick Start
-----------

[](#quick-start)

```
$cache = new GenericCache(__DIR__ . '/cache', 300);

$user = $cache->getOrFetch(1, function ($id) {
    return array(
        'id'   => $id,
        'name' => 'John Doe'
    );
});

print_r($user);
```

---

Configuration
-------------

[](#configuration)

GenericCache can be configured through its constructor:

```
$cache = new GenericCache(
    __DIR__ . '/cache', // Cache directory
    300,                // Cache lifetime in seconds
    false,              // Throw exceptions on errors
    null,               // Default log file (when logging is enabled)
    false               // Logging disabled by default
);
```

See [docs/API.md](docs/API.md) for detailed information about all available options.

---

Project Structure
-----------------

[](#project-structure)

```
GenericCache/
│
├── src/
│   └── GenericCache.php
│
├── docs/
│
├── examples/
│
├── integrations/
│
├── composer.json
│
├── LICENSE
│
├── CONTRIBUTING.md
│
└── README.md

```

---

Public API
----------

[](#public-api)

MethodDescription`get()`Retrieve cached data`set()`Store data in cache`has()`Check if a cache entry exists`getOrFetch()`Cache Aside strategy`getOrFetchStale()`Stale While Revalidate strategy`update()`Update an existing cache`invalidate()`Remove a cache entry`delete()`Alias of `invalidate()``invalidateAll()`Remove all cache files`cleanExpired()`Delete expired cache files`getRemainingTTL()`Get the remaining lifetime of a cache entry`getCachePath()`Get the full path to a cache file`stats()`Retrieve cache hit and miss statistics---

Examples
--------

[](#examples)

See the [Examples](examples/README.md) for runnable usage examples.

---

Integrations
------------

[](#integrations)

See the [Integration Examples](integrations/README.md) for examples of integrating GenericCache into different types of PHP applications.

---

Documentation
-------------

[](#documentation)

Complete documentation is available in the [`docs/`](docs/) directory.

- [API Reference](docs/API.md)
- [Architecture Overview](docs/ARCHITECTURE.md)
- [Changelog](docs/CHANGELOG.md)

---

When to Use GenericCache
------------------------

[](#when-to-use-genericcache)

GenericCache is a good fit when:

- You need a lightweight, reliable file-based caching solution for PHP.
- You want to reduce repeated database or API requests.
- You need cache consistency through atomic writes and file locking.
- You prefer a simple library with no external dependencies.
- You want a portable cache that is easy to deploy across a wide range of PHP hosting environments.

---

License
-------

[](#license)

This project is licensed under the MIT License.

###  Health Score

34

—

LowBetter than 75% of packages

Maintenance100

Actively maintained with recent releases

Popularity2

Limited adoption so far

Community2

Small or concentrated contributor base

Maturity28

Early-stage or recently created project

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

Unknown

Total

1

Last Release

0d ago

### Community

Maintainers

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

---

Tags

phpfilesystemcachelockingfile cachettlshared hostingatomic-writes

### Embed Badge

![Health badge](/badges/elfaruklabs-generic-cache/health.svg)

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

###  Alternatives

[awssat/laravel-visits

Laravel Redis visits counter for Eloquent models

973172.3k2](/packages/awssat-laravel-visits)[swayok/alternative-laravel-cache

Replacements for Laravel's redis and file cache stores that properly implement tagging idea. Powered by cache pool implementations provided by http://www.php-cache.com/

202583.7k9](/packages/swayok-alternative-laravel-cache)[rapidwebltd/rw-file-cache

RW File Cache is a PHP File-based Caching Library. Its syntax is designed to closely resemble the PHP memcache extension.

15195.9k7](/packages/rapidwebltd-rw-file-cache)[jord-jd/do-file-cache

DO File Cache is a PHP File-based Caching Library. Its syntax is designed to closely resemble the PHP memcache extension.

1510.3k4](/packages/jord-jd-do-file-cache)[wendelladriel/cache-ttl-helper

Helper Enum for handling cache TTLs in a simple, easy and friendly way

2215.4k](/packages/wendelladriel-cache-ttl-helper)

PHPackages © 2026

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