Para instalar memcached en un entorno linux (debian), deberemos ejecutar la siguiente linea de código:
sudo apt-get install -y php-memcached
Para asegurar que se instaló correctamente solo hacer falta hacer un php -m para ver los módulos instalados y ver en un archivo php con el método phpinfo(), si el módulo de memcached corre correctamente.
Ahora en nuestro proyecto de phalconphp debemos ir al services.php y colocar el siguiente código para tener disponible el servicio de caché.
use Phalcon\Cache\Frontend\Data as FrontendData;
use Phalcon\Cache\Backend\Memcache as BackendMemcache;
// Set the models cache service
$di->set(
'modelsCache',
function () {
// Cache data for one day (default setting)
$frontCache = new FrontendData(
[
'lifetime' => 86400,
]
);
// Memcached connection settings
$cache = new BackendMemcache(
$frontCache,
[
'host' => 'localhost',
'port' => '11211',
]
);
return $cache;
}
);
$di->set('modelsManager',function() {
return new ModelsManager();
}
);
Ahora queda cachear las queries que queramos, este es un ejemplo con una query hecha en PHPQL.
$manager = $this->modelsManager;
$query = $manager->createQuery('SELECT * FROM Blog JOIN BlogCategorias WHERE BlogCategorias.slug = :slug:'
);
$query->cache(
[
'key' => 'blog-categorias',
'lifetime' => 3600
]
);
$calculadoras = $query->execute([
'slug' => $slug,
]);
De esta manera estamos cacheando una query para los próximos 3600 segundos.
También podemos realizar el cacheo con otro tipo de consulta como la siguiente:
$robots = $cache->get($cacheKey);
if ($robots === null) {
// $robots is null because of cache expiration or data does not exist
// Make the database call and populate the variable
$robots = Robots::find(
[
'order' => 'id',
]
);
// Store it in the cache
$cache->save($cacheKey, $robots);
}