---
title: "Sistema de cache — Cache::store y FileCache"
section: performance
slug: cache
description: "Sistema de cache de PrestaShop: Cache::store/retrieve, cache de ObjectModel, configurar Memcache/Redis y estrategias de invalidacion."
keywords: "prestashop cache Cache::store retrieve ObjectModel Memcache Redis FileCache invalidacion rendimiento"
last_updated: 2024-12-01
source_url: "https://ayudaprestashop.es/performance/cache"
---

# Sistema de cache — Cache::store y FileCache

> Sistema de cache de PrestaShop: Cache::store/retrieve, cache de ObjectModel, configurar Memcache/Redis y estrategias de invalidacion.

PrestaShop tiene un sistema de cache multicapa: cache en memoria por request, cache de Smarty para templates, y cache persistente con Memcache, Redis o sistema de archivos. Usar correctamente la cache puede reducir el tiempo de respuesta en un 70-90%.

## Cache en memoria (por request)

*Cache::store() y Cache::retrieve() — cache por request*

```php
<?php

// ── La clase Cache usa el sistema configurado (Memcache, Redis o FileCache) ──
// Cache::store() con clave string

$cacheKey = 'mymodule_products_lang' . (int) Context::getContext()->language->id;

// Intentar recuperar de cache
$products = Cache::retrieve($cacheKey);

if ($products === false) {
    // No esta en cache — hacer la query costosa
    $products = Db::getInstance()->executeS(
        (new DbQuery())
            ->select('p.id_product, pl.name, p.price')
            ->from('product', 'p')
            ->leftJoin('product_lang', 'pl',
                'p.id_product = pl.id_product AND pl.id_lang = ' . (int) Context::getContext()->language->id
            )
            ->where('p.active = 1')
            ->orderBy('p.date_add DESC')
    ) ?: [];

    // Almacenar en cache
    Cache::store($cacheKey, $products);
}

// ── Verificar si una clave existe ──
if (Cache::isStored($cacheKey)) {
    $data = Cache::retrieve($cacheKey);
}

// ── Eliminar una clave ──
Cache::clean($cacheKey);

// ── Eliminar claves por patron ──
Cache::clean('mymodule_*');  // Elimina todas las claves que empiezan por mymodule_

// ── IMPORTANTE: Cache::store sin TTL no tiene expiracion en algunos backends ──
// Para fijar TTL, algunos backends lo permiten pero la interfaz base no
```

## Cache del ObjectModel

*Cache automatica del ObjectModel*

```php
<?php

// El ObjectModel cachea las instancias automaticamente
// Una vez cargado, la segunda instancia con el mismo ID usa cache

$product1 = new Product(42, false, $idLang); // Query a la BD
$product2 = new Product(42, false, $idLang); // Cache hit — sin query

// ── Verificar si un objeto fue cargado (existe en BD) ──
if (!Validate::isLoadedObject($product1)) {
    // El objeto no existe en BD o ID invalido
    Tools::redirect('index.php?controller=404');
}

// ── Forzar recarga desde BD (desactivar cache) ──
ObjectModel::enableCache();
ObjectModel::disableCache(); // Desactiva la cache del OM
$product = new Product(42); // Siempre va a la BD
ObjectModel::enableCache();

// ── Usar el metodo existsInDatabase() ──
if (!Product::existsInDatabase(42, 'product')) {
    // El producto no existe
}

// ── Invalidar la cache del OM despues de actualizar ──
Product::resetStaticCache(); // Limpia la cache estatica de Product
// Esto es necesario si modificas directamente la BD sin usar el OM
```

## Cache de Smarty

*Gestionar la cache de templates Smarty*

```php
<?php

// ── La cache de Smarty guarda el HTML compilado ──
// Se limpia desde: BO → Parametros Avanzados → Rendimiento → Vaciar cache

// ── Limpiar la cache de Smarty desde un modulo ──
public function hookActionProductSave(array $params): void
{
    // Cuando se guarda un producto, limpiar la cache de Smarty
    // para que los cambios sean visibles inmediatamente
    Tools::clearAllCache();
    // o solo la cache de smarty:
    // $this->context->smarty->clearAllCache();
}

// ── Deshabilitar la cache de Smarty para un template especifico ──
// En el FrontController:
public function initContent(): void
{
    parent::initContent();

    // Desactivar cache para paginas dinamicas
    $this->context->smarty->disableCaching();
}

// ── En modo desarrollo: cache desactivada automaticamente ──
// Cuando _PS_MODE_DEV_ = true, Smarty no cachea los templates
```

## Memcache y Redis

| Backend de Cache | Configuracion | Recomendado para |
| --- | --- | --- |
| FileCache (por defecto) | Sin configuracion adicional | Desarrollo, servidores pequeños |
| Memcache | BO → Rendimiento → Memcache | Produccion, servidor dedicado |
| Memcached | BO → Rendimiento → Memcached | Produccion, multiples servidores |
| Redis | BO → Rendimiento → Redis | Produccion, alta disponibilidad |

## Estrategias de invalidacion

*Invalidar cache en hooks de actualizacion*

```php
<?php

// ── Patron: invalidar cache cuando los datos fuente cambian ──

public function install(): bool
{
    return parent::install()
        && $this->registerHook('actionObjectProductUpdateAfter')
        && $this->registerHook('actionObjectProductDeleteAfter')
        && $this->registerHook('actionObjectProductAddAfter');
}

// Cuando se actualiza un producto, invalidar toda la cache relacionada
public function hookActionObjectProductUpdateAfter(array $params): void
{
    $this->invalidateProductCache();
}

public function hookActionObjectProductDeleteAfter(array $params): void
{
    $this->invalidateProductCache();
}

public function hookActionObjectProductAddAfter(array $params): void
{
    $this->invalidateProductCache();
}

private function invalidateProductCache(): void
{
    // Limpiar claves especificas del modulo
    Cache::clean('mymodule_products_*');
    Cache::clean('mymodule_featured_*');

    // Limpiar toda la cache de Smarty si es necesario
    // Tools::clearAllCache(); // Solo si es imprescindible
}
```


---

*Fuente: [https://ayudaprestashop.es/performance/cache](https://ayudaprestashop.es/performance/cache). Version Markdown generada automaticamente para consumo por LLMs.*
