We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Connect to my Redis server?

Hi folks,

Just a basic question, how to use native Redis functions in my own class? I found a few examples of Redis for session storage but my requirement is pretty simple. I just need to read some data from my Redis server.

So in a simple php script i can do this. $redis = new Redis();

            $redis->connect("xxxxx", "6379");
            if( !$redis->ping() ) {
                    error_log("Unable to connect to redis ", $error_log_type, $error_log_file);
            }

            $value  = $redis->get("$key");

how can i do this in Phalcon ? I have php-redis is already installed and the above php file works fine.



77.7k
Accepted
answer

Add it to your service declarations:

$di->setShared('redis', function() use(&$config) {
    $redis = new \Redis;
    $redis->connect($config->redis->host, $config->redis->port);
    if($config->redis->auth) {
        $redis->auth($config->redis->auth);
    }
    return $redis;
);

Then in an InjectionAware (Controller) context:

$this->redis->get("key");

Thanks it worked ;)