⬡ Lacelium
⌘K
Version 2.x ▾

Cache Engine

Introduction

Some database queries and computational tasks performed by your application can take significant CPU time or I/O resources to complete. To improve application performance, Lacelium provides an expressive, unified API for caching data across multiple high-performance storage backends.

Configuration

Your application's cache configuration is located at config/cache.php. In this file, you may specify which cache driver you would like to be used by default throughout your application.

Lacelium supports popular caching backends out of the box:

  • file: Stores cached items in serialized files on disk under storage/cache. Ideal for small to mid-sized applications.
  • redis: In-memory key-value data store. Perfect for high-concurrency production deployments.
  • array: In-memory array cache for unit tests and local CLI debugging.
  • apcu: APCu shared memory cache for ultra-low latency single-server environments.

Basic Usage

You may access the cache system via the global cache() helper function or through the Lacelium\Core\Cache\CacheManager class.

Retrieving Items

The get method is used to retrieve items from the cache. If the item does not exist in the cache, null will be returned. You may pass a second argument specifying the default value you wish to be returned if the item does not exist:

$value = cache()->get('key');

$value = cache()->get('key', 'default_value');

Checking Item Existence

The has method may be used to determine if an item exists in the cache:

if (cache()->has('key')) {
    // The key exists in cache
}

Storing Items in the Cache

You may use the put method to store items in the cache. You must provide a key, a value, and the number of seconds the item should be stored for:

// Store an item for 10 minutes (600 seconds)
cache()->put('key', 'value', 600);

// Store an item indefinitely
cache()->forever('stats.monthly', $data);

Retrieve or Store (Remember)

Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist. You can do this with the remember method:

$users = cache()->remember('users.active', 3600, function () {
    return \App\Models\User::where('active', 1)->get();
});

Removing Items

You may remove items from the cache using the forget method:

cache()->forget('key');

// Clear the entire cache
cache()->flush();

Cache Tags

When using the redis driver, you can tag related cache items. Cache tags allow you to tag related items in the cache and then flush all cached values that have been assigned a given tag:

// Store tagged items
cache()->tags(['reports', 'finance'])->put('q3_revenue', $revenue, 86400);

// Flush all reports
cache()->tags('reports')->flush();

Clearing the Cache via CLI

You can quickly clear your application cache from the terminal:

php console cache:clear

Next Steps