Drivers
The Memcached Driver
Using the Memcached driver for caching and data storage.
Introduction
The Memcached driver provides a simple and efficient way to store and retrieve data in-memory using multiple Memcached pools.
It is based on the excellent Symfony Cache component and provides a convenient interface for interacting with Memcached servers.
Installation
Install the driver via composer by running:
composer require kipchak/driver-memcached
Initialise the Driver
Add the following line to your drivers/drivers.php file:
\Mamluk\Kipchak\Driver\Memcached\Memcached::iniitalise($container);
Configuration
The configuration in kipchak.memcached.php can be used to configure muliple Memached pools:
return [
'enabled' => true,
'pools' => [
'cache' => [
['host' => 'memcached', 'port' => 11211]
],
'sessions' => [
['host' => 'memcached', 'port' => 11211]
]
],
];
Please see the configuration file in the starter project at https://1x.ax/mamluk/kipchak/starter/~files/master/config/kipchak.memcached.php for full configuration details.
Usage
use Kipchak\Driver\Memcached\Memcached;
use Symfony\Contracts\Cache\ItemInterface;
// Get a specific pool
$cache = Memcached::get('cache');
$sessions = Memcached::get('sessions');
$value = $cache->get('my_cache_key', function (ItemInterface $item) {
$item->expiresAfter(3600);
return 'expensive computation result';
});
// Delete from cache
$cache->delete('my_cache_key');
Raw Connection
PSR-6 cannot express atomic operations such as add, increment or cas. For those, connection() returns the pool's underlying \Memcached client, the same one its cache adapter uses.
$memcached = \Kipchak\Driver\Memcached\Memcached::connection('cache');
$firstSeen = $memcached->add('myapi.nonce.abc', 1, 300); // false if the key already exists
Keys written through the raw connection are not namespaced by the adapter, so prefix your own keys.
Git Repository
The source code for this driver is available on 1x.ax at https://1x.ax/mamluk/kipchak/drivers/memcached.