nael_d / cachex
Cachex: A PHP caching library with in-memory and file-based storage, offering flexible options for TTL, tags, and namespaces.
Requires
- php: >=7.0.0
README
Cachex is a PHP caching library with in-memory and file-based storage, offering flexible options for TTL, tags, and namespaces.
Features
- PHP Compatibility: Works with PHP >= 7.0.0 minimum.
- Dual drivers supporting: Cachex supports both file-based and in-memory drivers. By default, file-based driver is enabled.
- Namespaces: Easily organize cache entries by namespaces and subfolders.
- Tags: Tagging cache entries gains you an elevated level of efficient managing multiple caches.
- Events: Take control for each caching event triggers with ability to create a custom event listeners.
- Versioning: Manage cache entries using versioning each entry to make it unique.
- Flexible Deletion: Delete specific cache entries based on namespaces, tags, or keys.
- Grace periods: Have you set a global TTL value for Cachex and you still want to give a last change for an important cached value before being wiped? Cachex gains you the ability to get expired cache entries with a grace period for each individual entry before complete invalidation.
- Customization: Cachex gains you the ability to customize it freely, such as: (cache files storage, default global TTL, default global grace period, events, namespaces, ...). You control each property!
Table of Contents
Installation
Cachex is available to be installed through Composer, basically require it in your project:
composer require nael_d/cachex
You are also able to download Cachex manually. Download Cachex and require src/Cachex.php
.
For a better release checking, we may suggest to review Releases page to pick up and review developing timeline, as it provides a clear listing of versions along with detailed descriptions of each release.
Getting Started
Once installed, the class Cachex
is ready for you.
💡
Cachex
class is available underCachex
namespace.
By default, Cachex supports both File-based
and In-Memory-based
caching drivers. The default configuration is File-based
.
Properties
While Cachex's properties are private, understanding their purpose can provide valuable insights into the library's functionality.
$cacheDirectory:
Default is
string '.cache/'
. Used to determine where file-based cached files are stored. The ending/
is mandatory.$namespace:
Default value is
string ''
. Used to namespace cache files, preventing collisions in complex project environments.$defaultTtl:
Default is
int 300
. Default time-to-live for cache entries (in seconds).$gracePeriod:
Default is
int 0
. Used to extend expiration time for cache entries (in seconds).$enabled:
Default is
bool false
. Caching strategy: file-based drivertrue
or in-memory-based driverfalse
.$inMemoryCache:
Type is
array
. Used to store caches entries in case of using in-memory-bsaed driver.$builtInEvents:
Type is
array
. A built-in event hooks for customizing cache behavior and integrating with other components of your application:cache_set
: Triggered when Cachex creates or updates a cached entry.cache_clear
: Triggered when Cachex clears a specific cached entry by singlular or multiple keys.cache_truncate
: Triggered when Cachex wipes all cached entries, all at once.cache_clear_by_tag
: Triggered when Cachex wipes all cached entries with a specific singular or multiple tags.cache_event_registered
: Triggered when Cachex detects a new custom event hook has been registered.
$events:
Type is
array
. Used to store custom events and hooks.
Methods
Cachex offers flexible methods for storing, retrieving, and removing cache entries with support for namespaces, tags, and expiration.
getCacheDirectory():
Retrieves the current directory path where cache files are stored.
Usage:
echo \Cachex\Cachex::getCacheDirectory(); // outputs: ".cache/"
setCacheDirectory():
Sets the directory path for storing cache files.
Usage:
\Cachex\Cachex::setCacheDirectory('.cache/');
enable():
Enables or disables the caching system, switching between file-based or in-memory storage.
Parameters:
bool $enabled
: Default istrue
, refers to useFile-based
driver.false
refers to useIn-Memory-based
driver.
Usage:
\Cachex\Cachex::enable(); // default is `true` => file-based driver. \Cachex\Cachex::enable(false); // `false` => in-memory-based driver.
isEnabled():
Checks if the cache is enabled (file-based driver) or disabled (in-memory driver).
Usage:
\Cachex\Cachex::isEnabled(); // `true` => file-based driver. \Cachex\Cachex::isEnabled(); // `false` => in-memory driver.
setNamespace():
Sets a custom namespace to group cache entries, allowing cache entries isolation.
Parameters:
string $namespace
: The namespace to set.
💡 Dashes
-
and Underscores_
are only allowed to avoid OS files and directories conflicts.Usage:
\Cachex\Cachex::setNamespace('my_custom_namespace'); // `true` => file-based driver.
If the namespace contains
/
, it'll be treated as a subfolders path to store all cache entries in the currentCachex::$cacheDirectory
.Usage:
$namespace = 'my/custom/namespace'; \Cachex\Cachex::setNamespace($namespace); // cache entries are stored in $cacheDirectory/$namespace
💡 To isolate cache stores, configure distinct namespaces for each layer. The first namespace set will be propagated to subsequent layers unless explicitly changed.
setDefaultTtl():
Sets the default time-to-live (TTL) for cache entries in seconds.
Parameters:
int $seconds
: Default is300
, The TTL in seconds.
Usage:
\Cachex\Cachex::setDefaultTtl(60); // 1 minute
setGracePeriod():
Sets the default grace period (in seconds) after cache expiration before it's considered stale.
Parameters:
int $seconds
: Default is0
, The grace period in seconds.
Usage:
\Cachex\Cachex::setGracePeriod(10); // 10 seconds grace-period to extend all cache entries before expiration.
getTtl():
Retrieves the current global TTL.
Usage:
\Cachex\Cachex::getTtl(); // (int) 300
getGracePeriod():
Retrieves the current global grace period for cache expiration.
Usage:
\Cachex\Cachex::getGracePeriod(); // (int) 0
set():
Stores a cache entry with the specified key, value, TTL, version, and associated tags. It triggers
cache_set
event hook (if declared) when completed.Parameters:
string $key
: Required. The cache key.mixed $value
: Required. The data to cache.int $ttl
: Optional. The time-to-live in seconds for that cache entry.string $version
: Optional. The version of the cache entry.array $tags
: Optional. The tags associated with the cache entry.
Usage:
// Basic caching scenario, uses default settings: \Cachex\Cachex::set('cache_1', 'first value'); // Cached entry with an explicit TTL value: \Cachex\Cachex::set('cache_2', '2nd value', 400); // Cached entry with a `time()` unix timestamp-value version: \Cachex\Cachex::set('cache_3', '3rd value', null, 1732660520); // Cached entry with tags: \Cachex\Cachex::set('cache_4', '4th value', null, null, ['cp-login', 'tbl_users']);
get():
Retrieves the cached value for the specified key, considering custom grace period or specific version expecting.
Parameters:
string $key
: Required. The cache key.string $expectedVersion
: Optional. The expected version of that cache entry.int $gracePeriod
: Optional. The grace period for that cache entry (in seconds).
Usage:
// Basic getting scenario, uses default settings: echo \Cachex\Cachex::get('cache_1'); // outputs: "first value" // Getting cached entry with a custom grace period allowance: echo \Cachex\Cachex::get('cache_2', null, 120); // +120 seconds grace period // outputs: "2nd value"
Cached entries with versions are deleted if the wrong version is requested, regardless of expiration.
// cached entry key but wrong version echo \Cachex\Cachex::get('cache_3', 1444337859); // outputs: NULL
setThenGet():
Sets and immediately retrieves that cache entry, overwriting existing value.
Parameters: Same as
set()
method.Usage:
// new cached entry: echo \Cachex\Cachex::setThenGet('instant-caching', 'speedy!'); // outputs: "speedy!" // overwriting exist value: echo \Cachex\Cachex::setThenGet('cache_4', 'Overwritten!'); // outputs: "Overwritten!"
getOrSet():
Retrieves the cache entry if available, otherwise sets and returns it.
Parameters:
string $key
: Required. The cache key.mixed $value
: Required. The data to cache (in case of invalid$key
entry).int|null $ttl
: Optional. Time-to-live in seconds.string|null $version
: Optional. The version for cache invalidation.array $tags
: Optional. The tags for cache management.int|null $gracePeriod
: Optional. The grace period in seconds.
Usage:
// Getting an exist cached entry: \Cachex\Cachex::getOrSet('cache_1', "A value that won't be re-set due to its validity."); // outputs: "first value" // Creating a new cached entry and return it due to its invalidity case: \Cachex\Cachex::getOrSet('possible-key', 'Rumored data 🙄'); // outputs: "Rumored data 🙄"
getThenClear():
Performs a "fetch and delete" operation on a cache entry.
Parameters: Same as
get()
method.Usage:
$data = \Cachex\Cachex::getThenClear('cache_1'); echo $data; // outputs: "first value" echo \Cachex\Cachex::get('cache_1'); // outputs: NULL
clear():
Deletes a specific cache entry individually or multiple by its key. It triggers
cache_clear
event hook (if declared) when completed.Parameters:
string|array $key
: Required. The Cache key.
Usage:
// delete one cache entry: \Cachx\Cachx::clear('cache_2'); // return true // delete multiple cache entry: \Cachx\Cachx::clear(['cache_3', 'cache_4']); // return true
clearByTag():
Clears cache entries associated with the specified tags. It triggers
cache_clear_by_tag
event hook (if declared) when completed.Parameters:
string|array $tags
: Required. The tags to clear.
Usage:
// delete all cache entries within one tag: \Cachx\Cachx::clearByTag('cp-login'); // return true // delete all cache entries within multiple tags: \Cachx\Cachx::clearByTag(['cp-login', 'tbl_users']); // return true
clearAll():
Clear all cache entries at once. It triggers
cache_truncate
event hook (if declared) when completed.Usage:
// wipes all cache entries, everything! \Cachex\Cachex::clearAll();
getRegisteredEvents():
Retrieves an array of all registered event names, including built-in and custom events.
Usage:
$events = \Cachex\Cachex::getRegisteredEvents(); print_r($events); // print-out the array list
registerEvent():
Registers a custom event, or declare a built-in event, with a callback function to be executed when the event is triggered. It triggers
cache_event_registered
event hook each time you create a new custom event; declaring a built-in events won't trigger it.Ensure that built-in events are declared before they are triggered to avoid unexpected behavior.
Parameters:
string $eventName
: Required. The name of the event.callable $callback
: Required. The callback function to be executed when the event is triggered.
Usage:
// Declare built-in event hook: \Cachex\Cachex::registerEvent('cache_clear', function ($key) { error_log("The cache entry (`{$key}`) has been deleted.\n", 3, "my-errors.log"); }); // Create a new custom event hook: \Cachex\Cachex::registerEvent('delete_guest_footprint', function (...$params) { // let's say that you want to delete all cache entries within multiple tags. // instead of using `clearByTag()` each time you want, you create an event. // you are free to write your PHP code to execute ... // `array $params` is ready for you. // in addition to your code, clear cache entries within this tags: \Cachex\Cachex::clearByTag(['tbl_guests', 'tbl_carts', 'trending_items']); });
triggerEvent():
Triggers a registered event and executes all associated callbacks with the given arguments.
To ensure correct event handling, avoid direct invocation of built-in event callbacks. Let Cachex manage the built-in events lifecycle.
Parameters:
string $eventName
: Required. The name of the event to trigger.mixed ...$args
: Optional. The arguments to pass to the event callbacks.
Usage:
// Trigger an event with three parameters (you process them as well when declaring): \Cachex\Cachex::triggerEvent('delete_guest_footprint', 'first parameter', 21, false);
Troubleshooting
If you're experiencing issues, check the following:
- Cache Directory Permissions: Ensure that the cache directory is writable by the web server.
- TTL Expiration: Make sure the TTL is being set correctly. Cache will be automatically deleted once the TTL expires.
- Memory-based Cache: If you're using the memory driver, ensure that the server has sufficient memory.
Contributing
Cachex is an open-source project and contributions are welcome! To contribute, please fork the repository, create a new branch, and submit a pull request with your changes.
License
This project is licensed under the Mozilla Public License 2.0 (MPL-2.0). You are free to use, modify, and distribute this library under the terms of the MPL-2.0. See the LICENSE file for details.