Skip to content

Runtime Caches#

Runtime caches store objects created during the runtime of the script and are automatically discarded after the script terminates. Runtime caches are especially useful when objects are fetched by different APIs, each requiring separate requests. By using a runtime cache, you have two advantages:

  1. If the API allows it, you can delay fetching the actual objects and initially only tell the runtime cache that at some point in the future of the current request, you need the objects with the given ids. If multiple APIs do this one after another, all objects can be fetched using only one query instead of each API querying the database on its own.
  2. If an object with the same ID has already been fetched from database, this object is simply returned and can be reused instead of being fetched from database again.

IRuntimeCache#

Every runtime cache has to implement the IRuntimeCache interface. It is recommended, however, that you extend AbstractRuntimeCache, the default implementation of the runtime cache interface. In most instances, you only need to set the AbstractRuntimeCache::$listClassName property to the name of database object list class which fetches the cached objects from database (see example).

Usage#

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php
use wcf\system\cache\runtime\UserRuntimeCache;

$userIDs = [1, 2];

// first (optional) step: tell runtime cache to remember user ids
UserRuntimeCache::getInstance()->cacheObjectIDs($userIDs);

// […]

// second step: fetch the objects from database
$users = UserRuntimeCache::getInstance()->getObjects($userIDs);

// somewhere else: fetch only one user
$userID = 1;

UserRuntimeCache::getInstance()->cacheObjectID($userID);

// […]

// get user without the cache actually fetching it from database because it has already been loaded
$user = UserRuntimeCache::getInstance()->getObject($userID);

// somewhere else: fetch users directly without caching user ids first
$users = UserRuntimeCache::getInstance()->getObjects([3, 4]);

Example#

php
```php/api/caches/UserRuntimeCache.class.php ```

Last update: 2021-04-23