Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Using Redis subscribe method
  • Hello,
    Is there a way to use the redis subscribe or psubscribe method and read the happening message with the actual core class Redis ?
    Thanks for the help.
  • HarroHarro
    Accepted Answer
    The Redis class passes every command as-is through to Redis, so I don't see an immediate reason why that shouldn't work.
  • I agree, sorry for my bad explanations.
    The command is executed properly and I can get the result but I want to stay in listening to get the datas when something is published by another client.

    Exemple

    My application publish something :

    $redis->publish('event', 'data');

    And in a task I want to have maybe something like that to be able to read the response :

    while($result = $redis->subscribe('event'))
    {
        print_r($result);
    }
  • HarroHarro
    Accepted Answer
    My Redis knowledge isn't at that level, I don't know what that mechanism exactly works.

    But if that requires the connection to stay open between requests, that you'll have a challenge in the PHP world...
  • Thanks, I will try to find a solution
  • Finally I have override the Redis class to had a new function like that :

    <?php
    class Redis extends \Fuel\Core\Redis
    {
        public function psubscribe($pattern, $callback)
        {
            $args = array('PSUBSCRIBE', $pattern);

            $command = sprintf('*%d%s%s%s', 2, CRLF, implode(array_map(function($arg) {
                return sprintf('$%d%s%s', strlen($arg), CRLF, $arg);
            }, $args), CRLF), CRLF);
           
            for ($written = 0; $written < strlen($command); $written += $fwrite)
            {
                $fwrite = fwrite($this->connection, substr($command, $written));
                if ($fwrite === false)
                {
                    throw new \RedisException('Failed to write entire command to stream');
                }
            }
           
            while (!feof($this->connection))
            {
                try
                {
                    $response = $this->readResponse();
                    $callback($response);
                }
                catch(\RedisException $e)
                {
                    \Log::warning($e->getMessage(), 'Redis::readResponse');
                }
            }
            return true;
        }
    }

    If you see a better way, let me know.
  • HarroHarro
    Accepted Answer
    Can you create a ticket for this at http://github.com/fuel/core/issues, with the use case, and this proposed solution? This response will get lost otherwise.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion