Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

PHP License Status

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?

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

  • 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

  • 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

  • PHP 5.6 or later
  • Writable cache directory

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:

<Files "*">
    Require all denied
</Files>

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

Composer

composer require elfaruklabs/generic-cache

Install the package and include Composer's autoloader:

require 'vendor/autoload.php';

use ElfarukLabs\Cache\GenericCache;

Manual Installation

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

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

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

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 for detailed information about all available options.


Project Structure

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

Public API

Method Description
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

See the Examples for runnable usage examples.


Integrations

See the Integration Examples for examples of integrating GenericCache into different types of PHP applications.


Documentation

Complete documentation is available in the docs/ directory.


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

This project is licensed under the MIT License.

About

No description, website, or topics provided.

Resources

Contributing

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages