Caching in PHP: Redis, Memcached, and Built-in Solutions (Advanced Level)

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Caching in PHP: Redis, Memcached, and Built-in Solutions: Advanced Level



In modern web development, application performance directly impacts user experience, conversion rates, and search engine rankings. Caching is one of the most effective ways to speed up PHP applications, reduce database load, and decrease response time. At an advanced level, a developer needs not only to connect Redis or Memcached but also to understand invalidation strategies, data serialization, configuration tuning, and choosing the right tool for a specific task. In this article, we will cover three key approaches: Redis, Memcached, and built-in PHP solutions (OPcache, APCu), as well as practical examples and anti-patterns.



1. Built-in Solutions: OPcache and APCu



Before connecting external services, it is worth making the most efficient use of what is already available in PHP. Built-in mechanisms operate at the interpreter level and do not require installing additional software.



1.1. OPcache

OPcache (formerly Zend Optimizer+) compiles and stores PHP scripts as bytecode in shared memory. This eliminates the need to parse and compile code on every request. For most production projects, OPcache is enabled by default, but its configuration is critically important.



Recommended php.ini settings:

opcache.enable=1opcache.memory_consumption=128opcache.interned_strings_buffer=16opcache.max_accelerated_files=10000opcache.revalidate_freq=2opcache.fast_shutdown=1


Important: In development mode, set opcache.revalidate_freq=0 and opcache.validate_timestamps=1 so that file changes are applied immediately.



1.2. APCu (APC User Cache)

APCu provides a user cache in shared memory. It is ideal for storing small, frequently requested data: computation results, configurations, HTML fragments.



Example of using APCu:

// Save data to cache for 300 secondsapcu_store('user_profile_' . $userId, $profileData, 300);

// Retrieve dataif (apcu_exists('user_profile_' . $userId)) { $profile = apcu_fetch('user_profile_' . $userId);} else { // Generate data $profile = getUserProfileFromDB($userId); apcu_store('user_profile_' . $userId, $profile, 300);}


Limitations: APCu works only within a single server. In a clustered architecture, it does not synchronize between nodes, making it unsuitable for distributed systems.



2. Memcached: Simplicity and Speed



Memcached is a distributed in-memory caching system. Its main advantage is high speed and simplicity. Memcached does not support persistence (data is stored only in RAM) and has no built-in replication mechanisms, making it ideal for temporary caching.



2.1. Connection and Basic Usage

// Establish connection$memcached = new Memcached();$memcached->addServer('localhost', 11211);

// Save data with TTL of 600 seconds$memcached->set('user_123', ['name' => 'Ivan', 'email' => 'ivan@example.com'], 600);

// Retrieve data$user = $memcached->get('user_123');if ($memcached->getResultCode() === Memcached::RES_NOTFOUND) { // Data not found — load from DB $user = fetchUserFromDB(123); $memcached->set('user_123', $user, 600);}


2.2. Advanced Techniques with Memcached

  • CAS (Check And Set): Allows atomic updates of data, avoiding race conditions.
  • Multi-get: Batch retrieval of keys reduces the number of network calls.
  • Increments: For counters (e.g., view counts), use $memcached->increment().




                
                

Blogs

Book Recommendations