Caché

Configuración

Laravel provee una API unificada para varios sistemas de caché. La configuración de la caché se encuentra en app/config/cache.php. En este archivo puedes especificar que controlador de caché te gustaría utilizar por defecto en tu aplicación. Laravel soporta sistemas de caché populares como Memcached y Redis listos para utilizar.

El archivo de configuración del caché también contiene otras opciones, las cuales se encuentran documentadas dentro del archivo, así que asegúrate de leerlas. Por defecto Laravel está configurado para utilizar el controlador de caché file, el cual guarda los objetos de caché serializados en el sistema de archivos. Para aplicaciones más grandes, se recomienda que utilices un sistema de caché en memoria como Memcached o APC. Puedes incluso configurar múltiples configuraciones de caché para el mismo controlador.

Cache Prerequisites

Base de datos

Cuando utilizas el controlador de caché database, deberás configurar una tabla que contenga los elementos del caché. A continuación puedes encontrar un ejemplo de código Schema para la tabla:

Schema::create('cache', function($table) {
    $table->string('key')->unique();
    $table->text('value');
    $table->integer('expiration');
});

Memcached

Using the Memcached cache requires the Memcached PECL package to be installed.

The default configuration uses TCP/IP based on Memcached::addServer:

'memcached' => [
    [
        'host' => '127.0.0.1',
        'port' => 11211,
        'weight' => 100
    ],
],

You may also set the host option to a UNIX socket path. If you do this, the port option should be set to ``:

'memcached' => [
    [
        'host' => '/var/run/memcached/memcached.sock',
        'port' => 0,
        'weight' => 100
    ],
],

Redis

Antes de utilizar la caché Redis con Laravel, necesitarás instalar el paquete predis/predis (~ 1.0) a través de Composer.

For more information on configuring Redis, consult its Laravel documentation page.

Uso del caché

Obtaining A Cache Instance

The Illuminate\Contracts\Cache\Factory and Illuminate\Contracts\Cache\Repository contracts provide access to Laravel's cache services. The Factory contract provides access to all cache drivers defined for your application. The Repository contract is typically an implementation of the default cache driver for your application as specified by your cache configuration file.

However, you may also use the Cache facade, which is what we will use throughout this documentation. The Cache facade provides convenient, terse access to the underlying implementations of the Laravel cache contracts.

For example, let's import the Cache facade into a controller:

<?php

namespace App\Http\Controllers;

use Cache;
use Illuminate\Routing\Controller;

class UserController extends Controller
{
    /**
     * Show a list of all users of the application.
     *
     * @return Response
     */
    public function index()
    {
        $value = Cache::get('key');

        //
    }
}

Accessing Multiple Cache Stores

Using the Cache facade, you may access various cache stores via the store method. The key passed to the store method should correspond to one of the stores listed in the stores configuration array in your cache configuration file:

$value = Cache::store('file')->get('foo');

Cache::store('redis')->put('bar', 'baz', 10);

Retrieving Items From The Cache

The get method on the Cache facade is used to retrieve items from the cache. If the item does not exist in the cache, null will be returned. If you wish, you may pass a second argument to the get method specifying the custom default value you wish to be returned if the item doesn't exist:

$value = Cache::get('key');

$value = Cache::get('key', 'default');

You may even pass a Closure as the default value. The result of the Closure will be returned if the specified item does not exist in the cache. Passing a Closure allows you to defer the retrieval of default values from a database or other external service:

$value = Cache::get('key', function() {
    return DB::table(...)->get();
});

Checking For Item Existence

The has method may be used to determine if an item exists in the cache:

if (Cache::has('key')) {
    //
}

Incrementing / Decrementing Values

The increment and decrement methods may be used to adjust the value of integer items in the cache. Both of these methods optionally accept a second argument indicating the amount by which to increment or decrement the item's value:

Cache::increment('key');

Cache::increment('key', $amount);

Cache::decrement('key');

Cache::decrement('key', $amount);

Retrieve Or Update

Sometimes you may wish to retrieve an item from the cache, but also store a default value if the requested item doesn't exist. For example, you may wish to retrieve all users from the cache or, if they don't exist, retrieve them from the database and add them to the cache. You may do this using the Cache::remember method:

$value = Cache::remember('users', $minutes, function() {
    return DB::table('users')->get();
});

If the item does not exist in the cache, the Closure passed to the remember method will be executed and its result will be placed in the cache.

También puedes combinar los métodos remember y forever:

$value = Cache::rememberForever('users', function() {
    return DB::table('users')->get();
});

Retrieve And Delete

If you need to retrieve an item from the cache and then delete it, you may use the pull method. Like the get method, null will be returned if the item does not exist in the cache:

$value = Cache::pull('key');

Storing Items In The Cache

You may use the put method on the Cache facade to store items in the cache. When you place an item in the cache, you will need to specify the number of minutes for which the value should be cached:

Cache::put('key', 'value', $minutes);

Instead of passing the number of minutes until the item expires, you may also pass a PHP DateTime instance representing the expiration time of the cached item:

$expiresAt = Carbon::now()->addMinutes(10);

Cache::put('key', 'value', $expiresAt);

The add method will only add the item to the cache if it does not already exist in the cache store. The method will return true if the item is actually added to the cache. Otherwise, the method will return false:

Cache::add('key', 'value', $minutes);

The forever method may be used to store an item in the cache permanently. These values must be manually removed from the cache using the forget method:

Cache::forever('key', 'value');

Removing Items From The Cache

You may remove items from the cache using the forget method on the Cache facade:

Cache::forget('key');

Adding Custom Cache Drivers

To extend the Laravel cache with a custom driver, we will use the extend method on the Cache facade, which is used to bind a custom driver resolver to the manager. Typically, this is done within a service provider.

For example, to register a new cache driver named "mongo":

<?php

namespace App\Providers;

use Cache;
use App\Extensions\MongoStore;
use Illuminate\Support\ServiceProvider;

class CacheServiceProvider extends ServiceProvider
{
    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        Cache::extend('mongo', function($app) {
            return Cache::repository(new MongoStore);
        });
    }

    /**
     * Register bindings in the container.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

El primer argumento pasado al método extend es el nombre del controlador. Esto se corresponderá con tu opción driver que hay en el fichero de configuración app/config/cache.php. El segundo argumento es una Closure que debería devolver una instancia de Illuminate\Cache\Repository. The Closure will be passed an $app instance, which is an instance of the service container.

La llamada a Cache::extend podría hacerse en el método boot del service por defecto App\Providers\AppServiceProvider que viene con Laravel, o puedes crear tu propio service provider para acoger la extensión - no olvidar registrar el proveedor en el array provider de config/app.php.

To create our custom cache driver, we first need to implement the Illuminate\Contracts\Cache\Store contract contract. So, our MongoDB cache implementation would look something like this:

<?php

namespace App\Extensions;

class MongoStore implements \Illuminate\Contracts\Cache\Store
{
    public function get($key) {}
    public function put($key, $value, $minutes) {}
    public function increment($key, $value = 1) {}
    public function decrement($key, $value = 1) {}
    public function forever($key, $value) {}
    public function forget($key) {}
    public function flush() {}
}

Sólo necesitamos implementar cada uno de esos métodos usando una conexión MongoDB. Una vez que nuestra implementación sea completada, podremos finalizar nuestro registro del controlador personalizado:

Cache::extend('mongo', function($app) {
    return Cache::repository(new MongoStore);
});

Once your extension is complete, simply update your config/cache.php configuration file's driver option to the name of your extension.

Si te estás preguntando dónde poner el código de tu controlador de caché personalizado, ¡considera hacerlo disponible en Packagist! O bien, podría crear un namespace Extensions dentro del directorio app. Sin embargo, se debe tener en cuenta que Laravel no tiene una estructura rígida de aplicación y se tiene la libertad de organizar la aplicación según tus preferencias.