Cache
Configuration
All cache related configs are stored inside config/cache.php
file. All options are documented there, follow comments.
Usage
Simply use the Cache
facade. However, if you have access to the application service container you can inject Assely/Cache/Cache
as dependency.
use Assely\Cache\Cache;
public function __construct(Cache $cache) {
$this->cache = $cache;
}
public function register() {
$value = $this->cache->get('key');
}
Getting Cache Value
To receive cache value simply call get
method.
Cache::get('key');
Checking Cache Existence
Call has
method to check if cache with specifed key already exsists.
if (Cache::has('key')) {
// ...have cache
}
Putting Cache Value
Use put
method to save value into cache. Third argument is cache expiration time, if this is not determined, it will use default config form config/cache.php
file.
Cache::put('key', $value, $expire);
Flushing Cache Value
For clearing cache call flush
method with key of cache that has to be flushed.
Cache::flush('key');
Cache Blade Directive
You can cache parts of your views by surrounding they with @cache
and @endcache
directives. On the next run, if cache is present and not expiried, content of the directive will never run. Instead, will be pulled from the cache.
@cache($key, $arguments)
{{-- content --}}
@endcache
Nesting Blocks
Cache directives can be nested, but you have to take into account that child cache blocks will not even be able to run until the parent cache expires.
@cache('cache.parent')
{{-- parent content --}}
@cache('cache.nested')
{{-- child content --}}
@endcache
@endcache
Adapters Caching
Passing an instance of Assely\Adapter\Adapter
as key results with timestamp-based caching. This is useful especially when your posts have heavy views (displays metas, terms etc.).
@foreach($movies->all() as $movie)
@cache($movie)
{{ $movie->meta('details')->get('release_date') }}
@endcache
@endforeach
This approach uses modified_at
date as part of cache key. On update, this timestamp changes and automaticaly invalidates cache.
Cache keys are constructed in the following way {classname}/{id}-{modified_at}
. Caching Assely\Adapter\Post
with id of 1 may produce Assely\Adapter\Post/1-1452636753
key.
Arguments
Default expiration time is configured in app/cache.php
, but if you want to have diffrent expire time for specifed cache block you can pass it as second argument.
@cache('cache.key', ['expire' => DAY_IN_SECONDS])
{{-- content --}}
@endcache