Cache Chilkat2 PHP Reference Documentation

Cache

Current Version: 11.7.0

Markdown version of this page for AI tools (v 11.7.0) · all AI docs

Chilkat.Cache

Store, retrieve, expire, and clean up cached text or binary data on disk.

Chilkat.Cache is a disk-based cache class for storing and retrieving text or binary items by unique key. It provides configurable cache roots, optional multi-level directory layout, expiration metadata, ETag metadata, cache lookup, fetch-status properties, expiration updates, and cleanup methods for deleting individual items, expired items, older items, or the entire cache.

Key-based storage

Store and retrieve cached items by unique key, without the application needing to manage the underlying cache filenames directly.

Text and binary data

Cache strings, byte data, files, or Chilkat buffer objects depending on the data form used by the application.

Expiration control

Associate cached items with expiration times, update expiration metadata, and check whether cached content is still usable.

ETag metadata

Store and retrieve ETag values for workflows that need HTTP-style cache validation or conditional re-fetch logic.

Configurable layout

Choose the cache root directory and use an optional multi-level directory structure to avoid too many files in a single folder.

Cleanup operations

Delete a single cached item, remove expired items, remove older items, or clear the entire cache when needed.

Common pattern: Configure the cache root, choose the key used to identify each item, check whether a valid cached copy exists, fetch or regenerate the content when needed, store it with expiration and optional ETag metadata, and periodically clean up expired or old cached items.

Object Creation

use Chilkat2\Cache;

try {
    $cache = new Cache();
    // ... use $cache ...
} catch (\Chilkat2\Exception $e) {
    echo $e->getClass(), '::', $e->getMethod(), " failed\n";
    echo $e->getMessage(), "\n";              // the LastErrorText of the failed call
}
public function __construct(array $properties = [])

Creates the object. The optional array sets properties in order, as if assigned one by one (new Cache(['VerboseLogging' => true, 'RaiseError' => false])); an unknown or read-only name throws Error. The class is defined by the chilkat2 extension (extension=chilkat2 in php.ini): there is no PHP file to include.

There is no close(): PHP frees the object when its last reference goes (unset($cache), $cache = null, or the end of the function or request). Objects returned by methods are independent and freed the same way. The class may be extended (class MyCache extends \Chilkat2\Cache); objects cannot be cloned or serialized.

public bool $RaiseError;

When true (the default), a method that fails throws Chilkat2\Exception. When false, it returns false (or null) instead, and the reason is in LastErrorText. Objects returned by a method inherit the value of the object that returned them.

Errors

Chilkat2\Exception extends RuntimeException: getMessage() is the failed call's full LastErrorText, getClass() its class ('Chilkat2\Cache') and getMethod() the method name. The object remains usable. Methods that look something up and find nothing return null without throwing (each such method says so), methods that answer a question (HasMember, IsUnlocked, ...) return a plain bool, and property reads and writes do not throw for Chilkat reasons.

Misuse always throws, whatever RaiseError is: a wrong argument type is a TypeError (exact types under declare(strict_types=1)), a missing or extra argument an ArgumentCountError, a string containing a NUL byte or an out-of-range integer a ValueError, and an unknown property (properties are case-sensitive) or a write to a read-only one an Error. Named arguments work with the parameter names shown.

Strings are passed and returned as UTF-8; binary data is a PHP string of bytes. Unlocking: call (new \Chilkat2\GlobalSettings())->UnlockBundle('...') once at startup.

Properties

DebugLogFilePath
public string $DebugLogFilePath;

If set to a file path, this property logs the LastErrorText of each Chilkat method or property call to the specified file. This logging helps identify the context and history of Chilkat calls leading up to any crash or hang, aiding in debugging.

Enabling the VerboseLogging property provides more detailed information. This property is mainly used for debugging rare instances where a Chilkat method call causes a hang or crash, which should generally not happen.

Possible causes of hangs include:

  • A timeout property set to 0, indicating an infinite timeout.
  • A hang occurring within an event callback in the application code.
  • An internal bug in the Chilkat code causing the hang.

More Information and Examples
top
LastErrorHtml
public readonly string $LastErrorHtml;

Provides HTML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorText
public readonly string $LastErrorText;

Provides plain text information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastErrorXml
public readonly string $LastErrorXml;

Provides XML-formatted information about the last called method or property. If a method call fails or behaves unexpectedly, check this property for details. Note that information is available regardless of the method call's success.

top
LastEtagFetched
public readonly string $LastEtagFetched;

Returns the ETag metadata associated with the most recently fetched cache item. An empty string means that the fetched item has no stored ETag.

Read after a fetch: This property describes the item returned by the most recent successful fetch operation, such as FetchBd, FetchSb, or FetchText.
ETags are opaque metadata: The cache stores and returns the string but does not interpret it. Applications commonly use an HTTP ETag with conditional requests such as If-None-Match.

top
LastExpirationFetchedStr
public readonly string $LastExpirationFetchedStr;

Returns the expiration date and time stored for the most recently fetched cache item, formatted as an RFC 822-style Internet date. An empty string represents an item with no expiration date.

Expiration is metadata: Fetching an expired item is still possible. Read LastHitExpired after the fetch to determine whether the returned entry is stale.

top
LastHitExpired
public readonly bool $LastHitExpired;

Returns true when the expiration time of the most recently fetched item is earlier than the current system date and time; otherwise returns false.

Expired does not mean deleted: Expiration marks an entry as stale. The file remains in the cache until it is replaced or removed by methods such as DeleteAllExpired or DeleteFromCache.

top
LastKeyFetched
public readonly string $LastKeyFetched;

Returns the application-defined key associated with the most recently fetched cache item.

Keys are not limited to URLs: A canonicalized URL is a common key for cached web content, but any unique string may be used. Reusing a key causes a save operation to replace the existing item for that key.

top
LastMethodSuccess
public bool $LastMethodSuccess;

Indicates the success or failure of the most recent method call: true means success, false means failure. This property remains unchanged by property setters or getters. This method is present to address challenges in checking for null or Nothing returns in certain programming languages. Note: This property does not apply to methods that return integer values or to boolean-returning methods where the boolean does not indicate success or failure.

top
Level
public int $Level;

Gets or sets the number of directory levels used beneath each cache root. Valid values are 0, 1, and 2.

ValueDirectory layout
0All cache files are stored directly in the cache root.
1Files are distributed among 256 first-level directories named 0 through 255.
2Files are distributed through two levels of 256 directories, allowing as many as 65,536 leaf directories per root.
Configure before use: Use the same level when reopening an existing cache. Changing the layout does not reorganize previously stored files and can prevent the object from locating them through their keys.

top
NumRoots
public readonly int $NumRoots;

Returns the number of cache-root directories that have been registered by calling AddRoot.

Multiple roots: A cache may span more than one directory or storage device. Configure the same root set when reopening a persistent cache so previously stored items remain discoverable.

top
VerboseLogging
public bool $VerboseLogging;

If set to true, then the contents of LastErrorText (or LastErrorXml, or LastErrorHtml) may contain more verbose information. The default value is false. Verbose logging should only be used for debugging. The potentially large quantity of logged information may adversely affect peformance.

top
Version
public readonly string $Version;

Version of the component/library, such as "10.1.0"

More Information and Examples
top

Methods

AddRoot
public function AddRoot(string $path): void

Adds $path as a root directory for the disk cache. Call this method once for each root that should participate in the cache.

For example, a cache distributed across D:\cacheRoot, E:\cacheRoot, and F:\cacheRoot is configured by calling this method three times.

Use dedicated writable directories: Cache cleanup methods can delete cache files beneath every configured root. Do not mix unrelated application files into a cache root.
Persistent configuration: Recreate the same roots and Level setting before accessing a cache created by an earlier process or application run.
top
DeleteAll
public function DeleteAll(): int

Deletes every cache item from all configured roots and returns the number of cache files removed. Multi-level subdirectories are retained.

Destructive operation: This cannot be limited to a key prefix or reversed. Use cache roots dedicated to Chilkat cache data.
top
DeleteAllExpired
public function DeleteAllExpired(): int

Deletes all cache items whose stored expiration time is earlier than the current system time and returns the number of files removed.

Non-expiring entries remain: Items saved without an expiration date are not removed by this method.
top
DeleteFromCache
public function DeleteFromCache(string $key): bool

Deletes the cache item identified by $key.

Return valueMeaning
trueThe item was deleted, or no item existed for the key.
falseThe item exists but could not be deleted, for example because of a filesystem permission or sharing error.
Idempotent deletion: A missing key is not treated as an error, which makes it safe to call this method when the application merely wants to ensure that an item is absent.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
DeleteOlderDt
public function DeleteOlderDt(DateTime $dt): int

Deletes cache items older than the cutoff date and time supplied in $dt.

Returns the number of cache files deleted, or -1 if an error occurs.

Different from expiration cleanup: Use DeleteAllExpired when the decision should be based specifically on each item's expiration metadata.
top
DeleteOlderStr
public function DeleteOlderStr(string $dateTimeStr): int

Deletes cache items older than the cutoff date and time supplied in $dateTimeStr as an RFC 822-style Internet date string.

Returns the number of cache files deleted, or -1 if an error occurs.

Date format: A typical value is Mon, 03 Aug 2026 12:00:00 GMT. Use DeleteOlderDt when the cutoff is already available as a CkDateTime.
top
FetchBd
public function FetchBd(string $key, BinData $bd): bool
Introduced in version 9.5.0.91

Retrieves the binary item identified by $key and loads its bytes into the BinData object supplied in $bd.

The key is application-defined, may contain any characters, and must uniquely identify the intended item.

Check the return value: Use the destination only when this method returns true. A failed lookup or filesystem error returns false.
Freshness: A successful fetch may return an expired item. Read LastHitExpired immediately afterward when stale data must not be used.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
FetchSb
public function FetchSb(string $key, StringBuilder $sb): bool
Introduced in version 9.5.0.91

Retrieves the text item identified by $key and loads its content into the StringBuilder supplied in $sb.

The key is application-defined, may contain any characters, and must uniquely identify the intended item.

Check the return value: Use the destination only when this method returns true. A failed lookup or filesystem error returns false.
Freshness: A successful fetch may return an expired item. Read LastHitExpired immediately afterward when stale data must not be used.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
FetchText
public function FetchText(string $key): ?string

Retrieves the text item identified by $key and returns its string content.

The key is application-defined, may contain any characters, and must uniquely identify the intended item.

Freshness is separate: A successful fetch can return an expired entry. Read LastHitExpired immediately afterward when the application requires only fresh data.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
GetEtag
public function GetEtag(string $key): ?string

Returns the ETag metadata stored with the cache item identified by $key.

Opaque value: Chilkat does not parse or validate the ETag. An application may store any auxiliary string here, although HTTP entity tags are the common use case.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
GetExpirationStr
public function GetExpirationStr(string $url): ?string

Returns the expiration date and time stored for the item identified by $url, formatted as an RFC 822-style Internet date string.

Argument name: Some language bindings name $url url for historical reasons. It is the cache key and does not need to be a URL.
No-expiration entries: An empty stored expiration represents an item that does not expire automatically.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
GetFilename
public function GetFilename(string $key): ?string

Returns the absolute filesystem path of the cache file associated with $key.

Implementation detail: Treat the returned path as diagnostic information. Applications should normally read, update, and delete entries through the Cache API rather than modifying cache files directly.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
GetRoot
public function GetRoot(int $index): ?string

Returns the directory path of the cache root at zero-based $index. Valid indexes range from 0 through NumRoots - 1.

On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns null). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
IsCached
public function IsCached(string $key): bool

Returns true if an item exists for $key, or false if the key is not present.

Presence is not freshness: This method does not imply that the entry is unexpired. Fetch the item and examine LastHitExpired, or read its expiration metadata, when freshness matters.

Never throws: false is an answer, not a failure.

top
SaveBd
public function SaveBd(string $key, string $expiration, string $etag, BinData $bd): bool
Introduced in version 11.0.0

Stores the contents of $bd as binary cache data under $key. If the key already exists, its data and metadata are replaced.

ArgumentPurpose
$keyThe unique application-defined cache key.
$expirationExpiration as an RFC 822-style Internet date string. Pass an empty string for no expiration.
$etagOptional ETag or application metadata. Pass an empty string when unused.
$bdThe BinData containing the bytes to save.
Expiration is not automatic deletion: An expired item remains present until it is replaced or explicitly removed. This permits stale-while-revalidate workflows but requires the application to check freshness.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
SaveTextDt
public function SaveTextDt(string $key, DateTime $expireDateTime, string $eTag, string $itemTextData): bool

Stores $itemTextData as a text cache item under $key, with the expiration date and time supplied in $expireDateTime. If the key already exists, its data and metadata are replaced.

$eTag is optional ETag or application metadata and may be an empty string. The key may contain any characters and may be any length, but it must uniquely identify the item.

Expiration does not delete: After the expiration time passes, the entry remains on disk and can still be fetched. Use LastHitExpired to detect staleness and a deletion method to remove it.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
SaveTextNoExpire
public function SaveTextNoExpire(string $key, string $eTag, string $itemTextData): bool

Stores $itemTextData as a non-expiring text cache item under $key. If the key already exists, its data and metadata are replaced.

$eTag is optional ETag or application metadata and may be an empty string.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
SaveTextStr
public function SaveTextStr(string $key, string $expireDateTime, string $eTag, string $itemTextData): bool

Stores $itemTextData as a text cache item under $key, with $expireDateTime providing the expiration time as an RFC 822-style Internet date string. If the key already exists, its data and metadata are replaced.

$eTag is optional ETag or application metadata and may be empty.

Date alternatives: Use SaveTextDt when the expiration is available as a CkDateTime, or SaveTextNoExpire for an entry without expiration.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
UpdateExpirationDt
public function UpdateExpirationDt(string $key, DateTime $expireDateTime): bool

Replaces the expiration date and time of the cache item identified by $key with the CkDateTime value supplied in $expireDateTime. The cached data and ETag are unchanged.

Existing item required: This method updates metadata; it does not create a new cache entry when the key is absent.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top
UpdateExpirationStr
public function UpdateExpirationStr(string $key, string $expireDateTime): bool

Replaces the expiration date and time of the cache item identified by $key with the RFC 822-style Internet date string supplied in $expireDateTime. The cached data and ETag are unchanged.

Argument name: Some language bindings name $key url; it is the cache key and does not need to be a URL. Use UpdateExpirationDt for a CkDateTime value.

Returns true on success. On failure it throws Chilkat2\Exception (or, with RaiseError set to false, returns false). $e->getMessage() (or the object's LastErrorText) explains why, and the object remains usable.

top