PHP code example of niktomo / kura

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

    

niktomo / kura example snippets


// config/kura.php
return [
    'prefix' => 'kura',

    // Version resolution — how Kura determines which data version to use
    'version' => [
        'driver'    => 'csv',                           // 'csv' or 'database'
        'csv_path'  => base_path('data/versions.csv'),  // path to versions.csv
        'cache_ttl' => 300,                             // cache all version rows in APCu for 5 min
    ],

    // Rebuild strategy — what happens when cache is missing
    'rebuild' => [
        'strategy' => 'sync',  // 'sync' | 'queue' (recommended for production) | 'callback'
    ],
];

use Kura\Loader\EloquentLoader;
use Kura\Loader\StaticVersionResolver;

$loader = new EloquentLoader(
    query: Station::query(),
    tableDirectory: base_path('data/stations'),
    resolver: new StaticVersionResolver('v1.0.0'),
);

use Kura\Loader\EloquentLoader;
use Kura\Contracts\VersionResolverInterface;

$loader = new EloquentLoader(
    query: Station::query(),
    tableDirectory: base_path('data/stations'),
    resolver: app(VersionResolverInterface::class),
);

use Kura\Loader\LoaderInterface;

class MyApiLoader implements LoaderInterface
{
    public function load(): \Generator { /* fetch & yield records */ }
    public function columns(): array   { /* column → type map */ }
    public function indexes(): array   { /* index definitions */ }
    public function primaryKey(): string { /* primary key column name */ }
    public function version(): string  { /* cache key identifier */ }
}

// config/kura.php
'csv' => [
    'base_path'     => storage_path('reference'),  // directory to scan
    'auto_discover' => true,
],

// config/kura.php
'tables' => [
    'products' => ['primary_key' => 'product_code'],
],

use Kura\Contracts\VersionResolverInterface;
use Kura\Facades\Kura;
use Kura\Loader\CsvLoader;

public function boot(): void
{
    // Use the container-bound resolver (configured in config/kura.php)
    $resolver = app(VersionResolverInterface::class);

    Kura::register('stations', new CsvLoader(
        tableDirectory: base_path('data/stations'),
        resolver: $resolver,
    ));

    // You can register multiple tables
    Kura::register('lines', new CsvLoader(
        tableDirectory: base_path('data/lines'),
        resolver: $resolver,
    ));
}

use Kura\Facades\Kura;

// Find by primary key
$station = Kura::table('stations')->find(1);

// Filter
$tokyoStations = Kura::table('stations')
    ->where('prefecture', 'Tokyo')
    ->get();

// Sort & paginate
$page = Kura::table('stations')
    ->where('prefecture', 'Tokyo')
    ->orderBy('name')
    ->paginate(20);

// Aggregates
$count = Kura::table('stations')->where('prefecture', 'Osaka')->count();
$maxLat = Kura::table('stations')->max('lat');
$avgLng = Kura::table('stations')->where('line_id', 1)->avg('lng');

// Cross-table filtering (lazy subquery)
$tokyoLineIds = fn() => Kura::table('lines')
    ->where('region', 'Kanto')
    ->pluck('id');
$stations = Kura::table('stations')
    ->whereIn('line_id', $tokyoLineIds)
    ->get();

return [
    // APCu key prefix
    'prefix' => 'kura',

    // TTL in seconds per cache type
    'ttl' => [
        'pks'        => 3600,   // rebuild trigger — expiry causes next query to rebuild
        'record'     => 4800,   // longer than ids so records survive across rebuilds
        // 'index'   => omit to match ids TTL including jitter (recommended)
        //              ids and indexes then expire together, preventing a window where
        //              index keys are missing while ids is still present
        'pks_jitter' => 600,    // random 0–N seconds added to ids and index TTL (thundering herd prevention)
    ],

    // Rebuild lock TTL (seconds). Set to 1.5–2× the expected Loader execution time.
    'lock_ttl' => 60,

    // Rebuild strategy
    'rebuild' => [
        // 'sync'     — rebuild synchronously in the current request
        // 'queue'    — async via Laravel queue job
        // 'callback' — custom callable; set 'callback' below
        'strategy' => 'sync',

        // Required when strategy = 'callback'
        // Example: dispatch to a Horizon priority queue
        // 'callback' => static function (\Kura\CacheRepository $repository): void {
        //     dispatch(new \App\Jobs\RebuildReferenceJob($repository->table()))
        //         ->onQueue('high');
        // },
        'callback' => null,

        // Used when strategy = 'queue'
        'queue' => [
            'connection' => null,   // queue connection (null = default)
            'queue'      => null,   // queue name (null = default)
            'retry'      => 3,      // max attempts
        ],
    ],

    // Version resolution
    'version' => [
        'driver' => 'database',             // 'database' or 'csv'

        // database driver
        'table'   => 'reference_versions',
        'columns' => [
            'version'      => 'version',      // column name for the version string
            'activated_at' => 'activated_at', // column name for activation timestamp
        ],

        // csv driver
        'csv_path' => '',                   // absolute path to versions.csv

        // Seconds to cache all version rows in APCu (0 = no cache, re-reads every request)
        'cache_ttl' => 300,
    ],

    // Cache warm endpoint
    'warm' => [
        'enabled'           => false,
        'token'             => env('KURA_WARM_TOKEN', ''),  // Bearer token (

// config/kura.php
'warm' => [
    'enabled' => true,
    'token'   => env('KURA_WARM_TOKEN', ''),
],

use Kura\Store\ArrayStore;

$store = new ArrayStore;
$repository = new CacheRepository(table: 'products', primaryKey: 'id', store: $store, loader: $loader);
csv
id,version,activated_at
1,v1.0.0,2024-01-01 00:00:00
2,v2.0.0,2024-06-01 00:00:00
ini
; JIT
opcache.enable = 1
opcache.enable_cli = 1
opcache.jit = tracing
opcache.jit_buffer_size = 128M

; igbinary serializer for APCu (