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.
Configurations
Cache Settings
Define which adapter you want to use simply by setting the CACHE_DRIVER environment variable. You can choose between memory, apcu, stream, memcached and redis.
# Using Memory CacheCACHE_DRIVER_CLI=memoryCACHE_DRIVER=memory# Using Apcu CacheCACHE_DRIVER_CLI=apcuCACHE_DRIVER=apcu# Using File CacheCACHE_DRIVER_CLI=streamCACHE_DRIVER=stream# Using MemcachedCACHE_DRIVER_CLI=memcachedCACHE_DRIVER=memcached# Using Redis ServerCACHE_DRIVER_CLI=redisCACHE_DRIVER=redis
Good to know: APCU is normally disabled when using the PHP CLI. For this reason, Zemit allows you to specify your cache driver for the CLI mode as well as the global cache mode.
# Cache Settings of the `memory` driverCACHE_DRIVER_CLI=memoryCACHE_DRIVER=memoryCACHE_MEMORY_ADAPTER=\Phalcon\Cache\Adapter\Memory
# Cache Settings of the `apcu` driverCACHE_DRIVER_CLI=apcuCACHE_DRIVER=apcuCACHE_APCU_ADAPTER=\Phalcon\Cache\Adapter\Apcu
# Cache Settings of the `file` driverCACHE_DRIVER_CLI=streamCACHE_DRIVER=streamCACHE_STREAM_ADAPTER=\Phalcon\Cache\Adapter\StreamCACHE_STREAM_DIR=<root>/private/cache/data/
# Cache Settings for the `memcached` driverCACHE_DRIVER_CLI=memcachedCACHE_DRIVER=memcachedCACHE_MEMCACHED_ADAPTER=\Phalcon\Cache\Adapter\LibmemcachedCACHE_MEMCACHED_HOST=127.0.0.1CACHE_MEMCACHED_PORT=11211CACHE_MEMCACHED_WEIGHT=100# or if you wish to set memcached configuration globallyMEMCACHED_HOST=127.0.0.1MEMCACHED_PORT=11211MEMCACHED_WEIGHT=100
# Cache Settings for the `redis` driverCACHE_DRIVER_CLI=redisCACHE_DRIVER=redisCACHE_REDIS_ADAPTER=\Phalcon\Cache\Adapter\RedisCACHE_REDIS_DEFAULT_SERIALIZER=1CACHE_REDIS_LIFETIME=3600CACHE_REDIS_SERIALIZER=CACHE_REDIS_HOST=127.0.0.1CACHE_REDIS_PORT=6379CACHE_REDIS_INDEX=1CACHE_REDIS_AUTH=CACHE_REDIS_PERSISTENT=0CACHE_REDIS_SOCKET=
Usage
// if the class is aware of injections$crypt =$this->cache;// if the container is present$crypt =$this->di->get('cache');// to access the shared db service$crypt =Di::getDefault()->get('cache');