PHP code example of solophp / cache

1. Go to this page and download the library: Download solophp/cache library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

solophp / cache example snippets




use Solo\Cache\Cache;
use Solo\Cache\Adapter\FileAdapter;

// Create file adapter
$adapter = new FileAdapter('/path/to/cache/directory');

// Create cache instance
$cache = new Cache($adapter);

// Store a value
$cache->set('user.123', ['name' => 'John', 'email' => '[email protected]'], 3600);

// Retrieve a value
$user = $cache->get('user.123');

// Check if key exists
if ($cache->has('user.123')) {
    echo "Cache hit!";
}

// Delete a key
$cache->delete('user.123');

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



use Solo\Cache\Cache;
use Solo\Cache\Adapter\RedisAdapter;
use Redis;

// Create Redis connection
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);

// Create Redis adapter (default MODE_THROW, prefix "cache:")
$adapter = new RedisAdapter($redis);

// Or with custom prefix and graceful error handling
$adapter = new RedisAdapter($redis, RedisAdapter::MODE_FAIL, 'myapp:');

// Create cache instance
$cache = new Cache($adapter);

// Use the cache
$cache->set('session.abc123', ['user_id' => 42], 7200);
$session = $cache->get('session.abc123');

// Switch error mode at runtime if needed
$adapter->setMode(RedisAdapter::MODE_FAIL);



// Set multiple values
$cache->setMultiple([
    'key1' => 'value1',
    'key2' => 'value2',
    'key3' => 'value3',
], 3600);

// Get multiple values
$values = $cache->getMultiple(['key1', 'key2', 'key3'], 'default');

// Delete multiple values
$cache->deleteMultiple(['key1', 'key2']);



use DateInterval;

// Cache for 1 hour
$cache->set('key', 'value', new DateInterval('PT1H'));

// Cache for 1 day
$cache->set('key', 'value', new DateInterval('P1D'));

// Cache for 30 days
$cache->set('key', 'value', new DateInterval('P30D'));

// Default mode - throws exceptions
$adapter = new FileAdapter('/path/to/cache');

// Graceful mode - returns defaults on errors
$adapter = new FileAdapter('/path/to/cache', FileAdapter::MODE_FAIL);

// Manual garbage collection
$deletedFiles = $adapter->gc(); // Returns number of deleted expired files