Skip to content

Quick start guide

Greg Bowler edited this page Apr 19, 2026 · 1 revision

1. Install the package

composer require phpgt/filecache

2. Construct a Cache

use GT\FileCache\Cache;

$cache = new Cache(
	__DIR__ . "/cache",
	60 * 5
);

The first argument is the directory where cache files will be stored. The second argument is the lifetime, in seconds. In this example, entries remain fresh for 5 minutes.

If we omit the second argument, the default lifetime is 1 hour.

There is also a third optional constructor argument for supplying a FileAccess instance directly. Most applications do not need that, but it is available for advanced integration and testing.

3. Load data via the cache

$weather = $cache->get("weather:london", function():array {
	return [
		"summary" => "Cloudy",
		"temperature" => 14,
	];
});

On the first call, the callback runs and its return value is written to a cache file. On later calls with the same key, the cached value is returned immediately until the entry expires.

4. Use a meaningful cache key

The cache key is the logical name of the entry:

$user = $cache->get("user:105:profile", fn() => loadUserProfile(105));

Keys do not need to be limited to filenames. The library safely escapes characters that would otherwise affect paths, so values like URLs can be used directly:

$page = $cache->get("https://example.com/products/105", fn() => fetchPage());

The stored filename still remains readable for debugging because it uses URL-style escaping rather than an opaque hash.

5. Adjust the getter to match your expected type

If we know the value should be a string, integer, float, boolean, date, array, or class instance, there are typed getters available:

$username = $cache->getString("user:105:name", fn() => "Cody");
$count = $cache->getInt("dashboard:visits", fn() => 0);

The full set of getters is covered in Type safety.

Clone this wiki locally