Cache

Configuration & usage

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 Cache
CACHE_DRIVER_CLI=memory
CACHE_DRIVER=memory

# Using Apcu Cache
CACHE_DRIVER_CLI=apcu
CACHE_DRIVER=apcu

# Using File Cache
CACHE_DRIVER_CLI=stream
CACHE_DRIVER=stream

# Using Memcached
CACHE_DRIVER_CLI=memcached
CACHE_DRIVER=memcached

# Using Redis Server
CACHE_DRIVER_CLI=redis
CACHE_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` driver
CACHE_DRIVER_CLI=memory
CACHE_DRIVER=memory
CACHE_MEMORY_ADAPTER=\Phalcon\Cache\Adapter\Memory

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');

Sources

Last updated