Installation Add the bundle to your Symfony project via Composer:
composer require druidvav/memcache-bundle
Enable the bundle in config/bundles.php:
return [
// ...
Druidvav\MemcacheBundle\DruidvavMemcacheBundle::class => ['all' => true],
];
Configuration
Define Memcache connection in config/packages/druidvav_memcache.yaml:
druidvav_memcache:
servers:
default:
host: '127.0.0.1'
port: 11211
weight: 1
First Use Case
Inject the MemcacheClient service and use it to cache a simple value:
use Druidvav\MemcacheBundle\Client\MemcacheClient;
class MyService
{
public function __construct(private MemcacheClient $memcache)
{
}
public function getCachedData()
{
$key = 'my_key';
$value = $this->memcache->get($key);
if ($value === false) {
$value = $this->fetchFromDatabase(); // Fallback logic
$this->memcache->set($key, $value, 3600); // Cache for 1 hour
}
return $value;
}
}
Caching Database Queries Use Memcache to reduce database load for repeated queries:
$cacheKey = 'user_' . $userId;
$user = $this->memcache->get($cacheKey);
if (!$user) {
$user = $this->userRepository->find($userId);
$this->memcache->set($cacheKey, $user, 300); // Cache for 5 minutes
}
Fragment Caching Cache parts of a Symfony Twig template:
{% cache 'sidebar_' ~ app.user.id (app.user) %}
{% include 'partials/sidebar.html.twig' %}
{% endcache %}
Note: Requires additional setup for Memcache-backed cache pool in Symfony.
Distributed Caching Use the same Memcache instance across multiple application servers for shared caching:
# config/packages/druidvav_memcache.yaml
druidvav_memcache:
servers:
distributed:
host: 'memcache-cluster'
port: 11211
weight: 2
TTL Management Dynamically set Time-To-Live (TTL) based on data volatility:
$ttl = $isFrequentlyUpdated ? 60 : 3600; // 1 min or 1 hour
$this->memcache->set($key, $data, $ttl);
Symfony Cache Adapter
Use the bundle’s adapter to integrate with Symfony’s CacheInterface:
$cache = $this->memcache->getAdapter();
$item = $cache->getItem('some_key');
Dependency Injection
Prefer constructor injection for MemcacheClient to ensure testability:
public function __construct(private MemcacheClient $memcache) {}
Connection Pooling Configure multiple servers for failover and load balancing:
druidvav_memcache:
servers:
primary:
host: 'memcache-primary'
port: 11211
weight: 1
secondary:
host: 'memcache-secondary'
port: 11211
weight: 1
Connection Issues
try {
$value = $this->memcache->get($key);
} catch (\MemcacheException $e) {
// Fallback to database or return default
return $this->fallbackLogic();
}
Data Serialization
$this->memcache->set('user', serialize($user), 3600);
$user = unserialize($this->memcache->get('user'));
json_encode()/json_decode() for JSON-serializable objects.TTL Misconfiguration
0 for TTL disables expiration. Use false to let Memcache manage it:
$this->memcache->set($key, $value, false); // No expiration
Key Collisions
$key = 'app:user:' . $userId; // Prefix keys for namespacing
Memory Limits
memcached-tool localhost:11211 stats
Enable Logging Configure Monolog to log Memcache operations:
# config/packages/monolog.yaml
handlers:
memcache:
type: stream
path: "%kernel.logs_dir%/memcache.log"
level: debug
channels: ["memcache"]
Check Server Status
Use memcache->getStats() to diagnose issues:
$stats = $this->memcache->getStats();
if ($stats['uptime'] === 0) {
throw new \RuntimeException('Memcache server is down');
}
Custom Serialization Override the default serializer via configuration:
druidvav_memcache:
serializer: App\Service\CustomMemcacheSerializer
Event Listeners Subscribe to Memcache events (e.g., cache misses) using Symfony’s event dispatcher:
$dispatcher->addListener(
MemcacheEvents::MISS,
[$this, 'onCacheMiss']
);
Fallback Strategies Implement a decorator pattern for fallback logic:
class FallbackMemcacheClient implements MemcacheClientInterface
{
public function __construct(
private MemcacheClient $memcache,
private FallbackService $fallback
) {}
public function get($key)
{
$value = $this->memcache->get($key);
return $value !== false ? $value : $this->fallback->get($key);
}
}
Default Server
If no server is specified, the bundle uses default. Ensure this is defined.
Weight Parameter Higher weights increase the likelihood of selecting a server for operations (useful for load balancing).
Compression
The bundle does not support compression by default. Use gzip at the Memcache server level if needed.
add() instead of set() to avoid overwriting existing keys accidentally.$keys = ['key1', 'key2', 'key3'];
$values = $this->memcache->getMulti($keys);
How can I help you explore Laravel packages today?