The Phalcon\Cache
namespace offers a Cache component, that implements the PSR-16 interface, making it compatible with any component that requires that interface for its cache.
Frequently used data or already processed/calculated
data, can be stored in a cache storage for easier and faster retrieval. Since Phalcon\Cache
components are written in Zephir, and therefore compiled as C code, they can achieve higher performance, while reducing the overhead that comes with getting data from any storage container. Some examples that warrant the use of cache are :
* You are making complex calculations and the output does not change frequently
* You are producing HTML using the same data all the time (same HTML)
* You are accessing database data constantly which does not change often.
Phalcon\Cache
components rely on Phalcon\Storage
components. Phalcon\Storage
is split into two categories : Serializers and Adapters.
Cache : In order to instantiate a new Phalcon\Cache
component, you will need to pass a Phalcon\Cache\Adapter\*
class in it or one that implements the Phalcon\Cache\Adapter\AdapterInterface
. For a detailed explanation on adapters and serializers, see below.
<?php
use Phalcon\Cache;
use Phalcon\Cache\AdapterFactory;
use Phalcon\Storage\SerializerFactory;
$serializerFactory = new SerializerFactory();
$adapterFactory = new AdapterFactory($serializerFactory);
$options = [
'defaultSerializer' => 'Json',
'lifetime' => 7200
];
$adapter = $adapterFactory->newInstance('apcu', $options);
$cache = new Cache($adapter);