Content · Web Development · PHP

Using APCu for Application-Level Caching

APCu stores application data in shared memory on a single PHP host, separate from OPcache.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 Admin

APCu stores application data in shared memory on a single PHP host, separate from OPcache.

What It Does and When to Use It


Store one small application value with an explicit TTL. APCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code.

Requirements, Inputs and Expected Behavior


Confirm the runtime, extension, environment variables, and permissions before running the examples in production. APCu cache contents are not shared across servers and disappear on restart.

Example 1: Basic Operation


Store one small application value with an explicit TTL.

<?php
if (!function_exists('apcu_enabled') || !apcu_enabled()) throw new RuntimeException('APCu is disabled');
apcu_store('greeting:v1','Hello',60);
echo apcu_fetch('greeting:v1');

Example 2: Behavior and Validation


Use the success output parameter because false can be a valid cached value.

<?php
$success=false;
$value=apcu_fetch('feature:maintenance',$success);
echo $success?'Key found':'Cache miss';

Practical Example: Application Use


Populate cache on miss with apcu_entry when a single-host APCu cache is appropriate.

<?php
$key='policy:revision:4';
$policy=apcu_entry($key,static fn()=>['max_items'=>20],120);
echo (int)$policy['max_items'];

Important Behavior and Edge Cases


The second example highlights: Use the success output parameter because false can be a valid cached value. The practical example adds: Populate cache on miss with apcu_entry when a single-host APCu cache is appropriate.

Comparison with Related Approaches


ApproachWhat changes
APCu versus Redis and OPcacheAPCu stores local application data, Redis is external and can be shared among hosts, and OPcache stores compiled code.
Choosing safelyDefine TTL, invalidation, and concurrency behavior separately from the cache storage API.

Common Beginner Mistakes


MistakeCorrect approach
Assuming a cache is shared across multiple serversConfirm process- and host-level cache scope; use a distributed store when needed.
Never invalidating cached dataSet a TTL or versioned cache key and test release-time invalidation.
Skipping operational constraintsAPCu cache contents are not shared across servers and disappear on restart.

Key Takeaways


  • APCu stores application data in shared memory on a single PHP host, separate from OPcache.
  • Populate cache on miss with apcu_entry when a single-host APCu cache is appropriate.
  • Define TTL, invalidation, and concurrency behavior separately from the cache storage API.
Share this resourceSend this page to someone who may find it useful.