Using Memcached with PHP 7

Using Memcached with PHP 7

Upgrading to PHP 7 has its challenges. Getting our code to work with the upcoming php-memcached release for PHP 7 was one of them.

Ever since the release of PHP 7 in December we have been eager to test this release in development. However, without extensions like xDebug (released March 3rd) and php-memcached we were unable to do so. Recently alpha versions of php-memcached 3 have become available and some of our developers have been using PHP 7 with these php-memcached releases since.

Most of the Memcached extension works as before, except for an important backward incompatible change: the removal of the cas_token parameter in both the get* and getMulti* methods. As you can read in the original pull request the cas_token parameter has been removed in favor of the Memcached::GET_EXTENDED flag, which will cause the get-method to return an array containing both the return value and the cas_token. The reason for this change is that overriding the get-methods in an extension (e.g. using a test suite like phpunit) caused issues when the cas_token was passed as a parameter by reference.

Since we've wrapped the original Memcached class, adapting our code was pretty easy. When constructing our Memcached wrapper, we set a property telling us whether we should use the extended return flag:

public function __construct()
{
    $this->useExtendedReturn = version_compare(phpversion('memcached'), '2.9.9', '>');
    //...
}

Then, in our own get-method (and similar in the other get* and getMulti* methods) we simply add an if-statement checking this property:

public function get($key, callable $cache_cb = null, &$cas_token = null)
{
    if ($this->useExtendedReturn) {
        $extendedReturn = $this->Memcached->get($key, $cache_cb, Memcached::GET_EXTENDED);
        if ($extendedReturn === Memcached::GET_ERROR_RETURN_VALUE) {
            return false;
        }

        $cas_token = $extendedReturn['cas'];
        return $extendedReturn['value'];
    }

    return $this->Memcached->get($key, $cache_cb, $cas_token);
}

If you've encountered other changes in the new php-memcached extension, please let us know in the comments below!

Leave a comment...

Leave a comment

Italic en bold

*Dit is italic*, en _dit ook_.
**Dit is bold**, en __dit ook__.

Links

Dit is een link naar [Procurios](http://www.procurios.nl).

Lijsten

Een lijst met bullets kan worden gemaakt met:
- Min-tekens,
+ Plus-tekens,
* Of een asterisk.

Een genummerde lijst kan worden gemaakt met:
1. Lijst-item nummer 1.
2. Lijst-item nummer 2.

Quote

Onderstaande tekst vormt een quote:
> Dit is de eerste regel.
> Dit is de tweede regel.

Code

Er kan een blok met code worden geplaatst. Door voor de tekst vier spaties te plaatsen, ontstaat een code-block.