PHP code example of cachly-dev / sdk

1. Go to this page and download the library: Download cachly-dev/sdk 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/ */

    

cachly-dev / sdk example snippets


use Cachly\CachlyClient;

$cache = new CachlyClient('redis://:[email protected]:6379');

// Set a value with TTL
$cache->set('user:42', ['name' => 'Alice', 'plan' => 'pro'], ttl: 300);

// Get a value
$user = $cache->get('user:42'); // ['name' => 'Alice', 'plan' => 'pro']

// Check existence
if ($cache->exists('user:42')) { ... }

// TTL refresh
$cache->expire('user:42', 600);

// Atomic counter
$count = $cache->incr('page:views');

// Delete
$cache->del('user:42');

$data = $cache->getOrSet(
    key: 'expensive:report',
    fn:  fn() => $db->runExpensiveReport(),
    ttl: 60,
);

use Cachly\CachlyClient;

$cache  = new CachlyClient(getenv('CACHLY_URL'));
$openai = new OpenAI\Client(getenv('OPENAI_API_KEY'));

$embedFn = fn(string $text) => $openai
    ->embeddings()
    ->create(['model' => 'text-embedding-3-small', 'input' => $text])
    ->data[0]->embedding;

$result = $cache->semantic()->getOrSet(
    prompt:              $userQuestion,
    fn:                  fn() => $openai->chat($userQuestion),
    embedFn:             $embedFn,
    similarityThreshold: 0.90,
    ttl:                 3600,
);

echo $result->hit
    ? "⚡ Cache hit (similarity={$result->similarity})"
    : "🔄 Fresh from LLM";
echo $result->value;

// config/cachly.php
return ['url' => env('CACHLY_URL')];

// AppServiceProvider
$this->app->singleton(CachlyClient::class, fn() => new CachlyClient(config('cachly.url')));

// In a controller / service
public function __construct(private CachlyClient $cache) {}

use Cachly\CachlyClient;
use Cachly\BatchOp;

$cache = new CachlyClient(
    url: $_ENV['CACHLY_URL'],
    batchUrl: $_ENV['CACHLY_BATCH_URL'] ?? null, // optional
);

$results = $cache->batch([
    BatchOp::get('user:1'),
    BatchOp::get('config:app'),
    BatchOp::set('visits', '42', ttl: 86400),
    BatchOp::exists('session:xyz'),
    BatchOp::ttl('token:abc'),
]);

$user  = $results[0]->value;       // string|null
$ok    = $results[2]->ok;          // bool
$found = $results[3]->exists;      // bool
$secs  = $results[4]->ttlSeconds;  // int (-1 = no TTL, -2 = key missing)