Skip to content

Commit 0e6c718

Browse files
committed
update docs
1 parent a68e8d5 commit 0e6c718

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

README.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,59 @@ Assuming you have setup Composer's autoloader, FluentCache can be found in the `
3737

3838
## Usage
3939

40+
The principal type that FluentCache provides is `CacheBuilder`. `CacheBuilder` is an immutable object that takes references to a cache and anonymous functions to generate a cache key, build cacheable objects, validate results, and hook an event dispatcher.
41+
42+
`CacheBuilder` handles the responsibility for, and obfuscates, the steps required to orchestrate the most common scenario for handling cached data:
43+
44+
* Check the cache for an object
45+
* If miss, build an object, set it in the cache, and return the object
46+
* If hit, return the object
47+
48+
Managing these steps, choosing what to profile, when to validate, or other cache-specific decision making isn't the responsibility of the calling code: the caller just wants to _get_ an object, it shouldn't care if it comes from a cache, if the data is stale, or the object is built for the first time. `CacheBuilder` separates this concern and encapsulates it, exposing custom logic hooks for reasonable flexibility.
49+
4050
```php
51+
class Memcache implements \Psr\SimpleCache\CacheInterface {}
52+
53+
class Dispatcher implements \Psr\EventDispatcher\EventDispatcherInterface {}
54+
55+
$result = (new CacheBuilder())
56+
->withCache(new Memcache(), function() : ?string {
57+
58+
// generate a cache key - if null is returned, then the cache will be ignored
59+
return 'foo';
60+
})
61+
->withCacheLifespanBuilder(function($result) : int {
62+
63+
// what is the ttl for objects set in the cache?
64+
return 1500;
65+
})
66+
->withCacheValidator(function($result) : bool {
67+
68+
// assert that cached object is valid when fetched
69+
if(!($result instanceof Bar)) {
70+
return false;
71+
}
72+
return $result->someProperty = 'some value';
73+
});
74+
->withBuilder(function() : object {
75+
76+
// build a cacheable object if cache miss
77+
return new Bar();
78+
})
79+
->withBuildValidator(function($result) : object {
80+
81+
// assert that post-cache miss built object is valid
82+
return $result instanceof Bar;
83+
})
84+
85+
// send cache and build stage events to trigger downstream actions such as profiling
86+
->withEventDispatcher(new Dispatcher())
87+
88+
// ...or set a lazy dispatcher to initialize when we attempt to fetch an object
89+
->withLazyEventDispatcher(function(CacheBuilder $this) : EventDispatcherInterface {
90+
return new Dispatcher();
91+
})
4192

93+
// fetch object from cache or build it and set it in the cache - the caller doesn't care!
94+
->get();
4295
```

0 commit comments

Comments
 (0)