1

I am trying to write a method which will do asynchronus memcache queries.

This is my simple get/set memcache client class.

Class MemcacheClient
{
    private $socket;

    private $reply;

    private $replies = array(
        'OK' => true,
        'EXISTS' => false,
        'DELETED' => true,
        'STORED' => true,
        'NOT_STORED' => false,
        'NOT_FOUND' => false,
        'ERROR' => null,
        'CLIENT_ERROR' => null, 
        'SERVER_ERROR' => null
    );

    public function __construct($host, $port)
    {
        $this->socket = stream_socket_client("$host:$port", $errno, $errstr);

        if(!$this->socket) {
            throw new Exception("$errst ($errno)");
        }
    }

    public function get($key)
    {
        $reply = $this->query("get $key");

        return $reply;
    }

    public function set($key, $value, $exptime = 0, $flags = 0)
    {
        return $this->query(array("set $key $flags $exptime ".strlen($value), $value));
    }

    public function aget($key, $function)
    {

    }

    public function process()
    {

    }

    public function hasTasks()
    {

    }

    private function query($query)
    {
        $query = is_array($query) ? implode("\r\n", $query) : $query;

        fwrite($this->socket, $query."\r\n");

        return $this->parseLine();
    }

    private function parseLine()
    {
        $line = fgets($this->socket);
        $this->reply = substr($line, 0, strlen($line) - 2);

        $words = explode(' ', $this->reply);

        $result = isset($this->replies[$words[0]]) ? $this->replies[$words[0]] : $words;

        if (is_null($result)) {
            throw new Exception($this->reply);
        }

        if ($result[0] == 'VALUE') {
            $value = fread($this->socket, $result[3] + 2);

            return $value;
        }

        return $result;
    }
}

I'm looking for something like

$memClient->aget('key', function($data) {echo $data;});

Any ideas how it could be implemented? Will appreciate any help.

Thanks!

  • Possible duplicate of [PHP threading call to a php function asynchronously](http://stackoverflow.com/questions/13846192/php-threading-call-to-a-php-function-asynchronously) – castis Oct 04 '16 at 12:35
  • I need something more special to my case.... Im not sure i can implement that in my code. Anything more please? – user3649628 Oct 04 '16 at 14:46
  • If you're looking for asynchronous, threads might be your only safe option outside of implementing this stuff elsewhere. Add in your question why you're looking to do this and maybe we can come up with something. – castis Oct 04 '16 at 14:51

0 Answers0