Uri Cache

The UriCache.php file is a class in the PHPFast framework that provides methods to cache and retrieve content based on the URI (Uniform Resource Identifier). This class helps in optimizing the performance of web applications by caching the output of specific URIs. Below is a detailed explanation of each method along with examples of how to use them.

__construct()

<?php
public function __construct($compression = 0, $type = 'html') {
    // Set the cache directory (assuming ROOT_PATH is defined)
    $this->cacheDir = ROOT_PATH . '/writeable/cache/';
    $this->compression = $compression;
    $this->headerType = $type;
    $this->cacheLogin = false;
}

Initializes the UriCache object with optional compression level and content type.

  • $compression: Compression level (0 = no gzip, 1-9 = gzip level).

  • $type: Content type (e.g., 'html', 'json').

  • Sets the cache directory.

  • Sets the compression level and content type.

  • Initializes the cache login state to false.

headers()

function headers($compress = -1)

Sends the appropriate HTTP headers for the cached content based on its type and compression settings.

  • $compress: Compression level (-1 to use default).

set()

function set($content)

Stores the given content in the cache after applying optional compression.

  • $content: Content to be cached.

  • return: Cached content or false if caching is disabled.

get()

function get()

Retrieves and returns cached content if available.

  • Note: if the file is gzip, it returns gzip data.

  • return: Cached content or null if not found.

delete()

Deletes a specific cached file.

  • return: true if the cache file is deleted, false otherwise.

has()

Checks if a cached file exists for the requested content.

  • return: true if the cache file exists, false otherwise

clear()

Removes all cached files, effectively clearing the cache storage.

  • return: true if the cache directory is cleared

Example

<?php
// Initialize the UriCache object
$uriCache = new UriCache(1, 'html');

// Check if the cache exists
if ($uriCache->has()) {
    // Retrieve and display the cached content
    $cachedContent = $uriCache->get();
    if ($cachedContent !== null) {
        echo $cachedContent;
        exit;
    }
}

// Generate the content to be cached
$content = '<html><body><h1>Welcome to PHPFast Framework</h1></body></html>';

// Save the content to the cache
$uriCache->set($content);

// Delete cache
$uriCache->delete();

// Clear cache
$uriCache->clear();

// Display the content
echo $content;

Last updated

Was this helpful?