PHP code example of modethirteen / fluent-cache

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

    

modethirteen / fluent-cache example snippets


class Memcache implements \Psr\SimpleCache\CacheInterface {}

class Dispatcher implements \Psr\EventDispatcher\EventDispatcherInterface {}

$result = (new CacheBuilder())
    ->withCache(new Memcache(), function() : ?string {

        // generate a cache key - if null is returned, then the cache will be ignored
        return 'foo';
    })
    ->withCacheLifespanBuilder(function($result) : int {

        // what is the ttl for objects set in the cache?
        return 1500;
    })
    ->withCacheValidator(function($result) : bool {

        // assert that cached object is valid when fetched
        if(!($result instanceof Bar)) {
            return false;
        }
        return $result->someProperty === 'some value';
    })
    ->withBuilder(function() : object {

        // build a cacheable object if cache miss
        return new Bar();
    })
     ->withBuildValidator(function($result) : object {

        // assert that post-cache miss built object is valid
        return $result instanceof Bar;
    })

    // send cache and build stage events to trigger downstream actions such as profiling
    ->withEventDispatcher(new Dispatcher())

    // ...or set a lazy dispatcher to initialize when we attempt to fetch an object
    ->withLazyEventDispatcher(function(CacheBuilder $this) : EventDispatcherInterface {
        return new Dispatcher();
    })
 
    // set a custom identifier to track this cache session in downstream event processors
    // ...session ids are automatically generated if not provided
    // ...session ids are re-generated everytime the immutable cache builder is cloned 
    ->withSessionId('123')
 
    // fetch object from cache or build it and set it in the cache - the caller doesn't care!
    ->get();