phasync
Swerve / cache

Method

Swerve::cache

The cache every worker shares, held by the master process.

Description#

public static Swerve::cache(): CacheInterface

A PSR-16 cache: see Cache for how it is layered and what it keeps.

Return values#

The same cache on every call CacheInterface

Examples#

Example 1Load once, then read from the cache
use Swerve\Swerve;

function load_user(int $id): array
{
    echo "loading user $id from the database\n";

    return ['id' => $id, 'name' => 'Ann'];
}

phasync::run(function () {
    foreach ([1, 1, 1] as $id) {
        $user = Swerve::cache()->get("user.$id");
        if (null === $user) {
            $user = load_user($id);
            Swerve::cache()->set("user.$id", $user, 60);   // for every worker, 60 seconds
        }
        echo "hello, {$user['name']}\n";
    }
});
Output
loading user 1 from the database
hello, Ann
hello, Ann
hello, Ann
Example 2
$cache = Swerve::cache();
$user  = $cache->get("user.$id") ?? load_user($id);
$cache->set("user.$id", $user, 60);

See also#

  • CacheThe cache every worker shares, from Swerve::cache(): a PSR-16 cache held by the master process, the least recently used entries evicted past --cache-size.
  • Swerve::claimWhen one worker at a time must do something