Abishek
Abishek

Reputation: 11691

How to change the connection info for Laravel 4 when using the redis driver?

I am using redis as the driver for caching data. The database configuration of Laravel has the ability to define the Redis connection information.

  'redis'       => array(
    'cluster' => true,
    'default' => array(
        'host'     => '127.0.0.1',
        'port'     => 6379,
        'database' => 0,
    ),
),

But if I wanted to have multiple connections defined and use a specific connection to use for the cache, how can I do this on Laravel 4. There is no connection configuration on cache.php where I can specify the redis connection name. It currently has a connection config that will be used if the cache driver is database.

EDIT

I just went through the Laravel code and when initializing the Redis Driver, it looks like Laravel is not looking into the connection. Is my understanding correct?

http://laravel.com/api/source-class-Illuminate.Cache.CacheManager.html#63-73

protected function createRedisDriver()
{
    $redis = $this->app['redis'];

    return $this->repository(new RedisStore($redis, $this->getPrefix()));
}

Upvotes: 0

Views: 4305

Answers (1)

fideloper
fideloper

Reputation: 12293

Laravel can handle multiple connections. See this question/answer on adding/using multiple database connections.

Once you define multiple connections for redis, you'll need to do some leg work to access those somewhere in your code. That might look something like this:

$redisCache = App::make('cache'); // Assumes "redis" set as your cache
$redisCache->setConnection('some-connection'); // Your redis cache connection
$redisCache->put($key, $value');

Edit

I'll add a little here to give you an idea of how to do this so you don't need the connection logic everywhere:

Most simply, you can bind an instance of your redis cache somewhere (perhaps a start.php or other app/start/*.php file) in your app:

App::singleton('rediscache', function($app){
    $redisCache = $app['cache'];
    $redisCache->setConnection('some-connection'); // Your redis cache connection
    return $redisCache;
});

Then, in your code, you can do this to cache:

$cache = App::make('rediscache');
$cache->put($key, $value); // Or whatever you need to do

You can also create a Service Provider if you have your own application library of code. You can register 'rediscache' within there and then use it in the same way in your application.

Hope that helps as a start - there are other code architectures - using Dependency Injection and maybe a repository to help organize your code further.

Upvotes: 5

Related Questions