We are moving our forum in GitHub Discussions. For questions about Phalcon v3/v4 you can visit here and for Phalcon v5 here.

Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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.6k
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 ;)