Predis Versions Save

A flexible and feature-complete Redis client for PHP.

v0.8.2

9 years ago

Predis is a flexible and feature-complete PHP (>= 5.3.2) client library for Redis.

This is a maintenance release for the 0.8 series. What follows is an overview of the new features and fixes introduced in this new release, for a more in-depth list of changes please see the CHANGELOG.

New features and changes

Fix for response parsing in pipelines

The main reason for this new patch release is to fix a bug introduced right before releasing v0.8.0 that prevented complex responses from Redis from being parsed correctly in command pipelines as reported on this issue. This bug didn't affect correctness of the data stored or returned by Redis, but prevented replies to certain commands such as HGETALL from being parsed by the client before returning to the user's code.

Predis-based session handler

A new class Predis\Session\SessionHandler has been added to provide an easy way to use Predis as a backend to store PHP's sessions on Redis. This new class is mainly intended for PHP >= 5.4 since it implements SessionHandlerInterface but it can be used with PHP 5.3 if a polyfill for this interface is provided by you or an external package in your dependencies (such as symfony/http-foundation just to name one).

<?php
$client = new Predis\Client('tcp://127.0.0.1', array('prefix' => 'sessions:'));
$handler = new Predis\Session\SessionHandler($client);
$handler->register();

See a more exhaustive example.

Predis service provider for Silex

Along with this release, the official service provider for Silex has been finally updated to use Predis v0.8 with a new version bump that brings some breaking changes when dealing with multiple clients configuration. These changes was necessary to better fit with the boot mechanism for service providers that was introduced a few months ago in Silex.

Additional notes

Downloads

v0.8.3

9 years ago

Predis is a flexible and feature-complete PHP (>= 5.3.2) client library for Redis.

This is a maintenance release for the 0.8 series shipping some new features and minor micro-optimizations. What follows is an overview of the new features and changes introduced in this new release, for a more in-depth list of changes please see the CHANGELOG.

New features and changes

CLIENT SETNAME and CLIENT GETNAME

Thanks to Raphael Stolt's pull request you can now use CLIENT SETNAME and CLIENT GETNAME.

New stream-based phpiredis connection backend

We've had a connection backend based on the phpiredis extension for quite some time now, but it required the socket extension to be loaded in order to work. Now there's a new connection backend which still relies on phpiredis to parse and serialize the Redis protocol, but internally uses PHP's native streams. One of the benefits of using streams is that they support persistent connections when used with plain FastCGI or php-fpm processes. Client configuration to make use of this connection backend is the same as usual, you just need to specify the Predis\Connection\PhpiredisStreamConnection class:

<?php
$client = new Predis\Client('tcp://127.0.0.1', array(
    'connections' => array(
        'tcp'  => 'Predis\Connection\PhpiredisStreamConnection',
        'unix' => 'Predis\Connection\PhpiredisStreamConnection',
    ),
);

TCP_NODELAY with stream-based connections (PHP >= 5.4.0 only)

One of the historic downsides of using stream-wrapped sockets has always been the impossibility of tinkering with socket options, but luckily for us the introduction of socket_import_stream() in PHP 5.4 removed this limitation. This make it possible to set the TCP_NODELAY socket option to enable or disable Nagle's algorithm using the tcp_nodelay connection parameter:

<?php
$client = new Predis\Client('tcp://127.0.0.1?tcp_nodelay=0');

You can effectively set any kind of socket option by yourself in your library or application's code with something like:

<?php
$client = new Predis\Client('tcp://127.0.0.1');
$socket = socket_import_stream($client->getConnection()->getResource());
socket_set_option($socket, SOL_TCP, TCP_NODELAY, 0);

Callable objects for$parameters in client constructor

Additionally to strings, arrays or even instances of Predis\Connection\ConnectionInterface, now the first argument of Predis\Client::__construct() can accept callable objects returning instances of Predis\Connection\ConnectionInterface. This may appear as an unnecessary addition, but it can reveal itself useful to create custom and self-contained solutions to handle complex configuration scenarios. As an (admittedly) extreme example, we relied on this feature to wrap the code needed to use client-side sharding to distribute keys among virtual nodes of replicated Redis instances without further changing the library's code.

Minor non-breaking change in Lua scripting abstraction

When instructing scripted commands to use all the arguments to populate the ARGV table and leave KEYS empty on Lua's side, developers were required to return FALSE (strictly boolean) from getKeysCount() in their command implementation. This choice didn't make much sense and now you can simply return 0. This change does not break existing code since 0 == FALSE in PHP.

Changes in redis-cluster distribution

Salvatore recently started working again on redis-cluster (that alone is an awesome news!) and commited a change raising the number of hash slots used for distribution, from 4096 to 16384. Our aggregated connection for redis-cluster has been updated accordingly, so pay attention when upgrading both Redis and Predis if you were brave enough having something based on it.

Additional notes

Downloads

v0.8.1

9 years ago

Predis is a flexible and feature-complete PHP (>= 5.3.2) client library for Redis.

This is a maintenance release for the 0.8 series. What follows is an overview of the new features and fixes introduced in this new release, for a more in-depth list of changes please see the CHANGELOG.

New features and changes

Client options

When using callables with client options accepting them, Predis now passes the current option instance as their second argument making it possible to get the default value for that option:

<?php
$options = array(
    'profile'  => function ($options, $option) {
        $profile = $option->getDefault($options);
        $profile->defineCommand('test', 'My\Command\TestCommand');

        return $profile;
    },
);

$client = new Predis\Client('tcp://127.0.0.1', $options);

Now you can use a callable with the connections option to initialize the instance of Predis\Connection\ConnectionFactoryInterface that will be used internally by the client to create the underlying connection:

<?php
$options = array(
    'connections' => function ($options, $option) {
        $factory = $option->getDefault($options);

        if (extension_loaded('phpiredis')) {
            $factory->define('tcp', 'Predis\Connection\PhpiredisConnection');
            $factory->define('unix', 'Predis\Connection\PhpiredisConnection');
        }

        return $factory.
    },
);

Client-side sharding based on node alias

There was this long-standing feature request that never got a decent solution shipped within the library in order to support named connections (distribution of nodes is based on their alias instead of the host:port pair), but now we have a generalized way to do that supported by both Predis\Cluster\Distribution\HashRing and Predis\Cluster\Distribution\KetamaPureRing and consists of passing a callable to the second argument of their constructors:

<?php
use Predis\Cluster\Distribution\HashRing;
use Predis\Connection\PredisCluster;

$options = array(
    'cluster' => function ($options) {
        $replicas = HashRing::DEFAULT_REPLICAS;

        $nodehash = function ($connection) {
            return $connection->getParameters()->alias;
        }

        $hashring = new HashRing($replicas, $nodehash);
        $cluster  = new PredisCluster($hashring);

        return $cluster;
    },
);

As you can see you can decide which kind of value to return from your callback, but keep in mind that everything will be casted to string by our hashring implementation.

Fix for edge case in Lua scripting abstraction

When leveraging the scripted commands abstraction Predis always tries to optimize things by using EVALSHA which, on the other hand, could fail with a -NOSCRIPT error if the Lua script referred by its SHA1 hash has not been cached by Redis yet. In these cases Predis automatically retries by issuing an EVAL command with the same arguments in addition to the whole Lua script body, but due to this bug the client wasn't using the original parseResponse() method from the initial command instance to parse the response.

Documentation

Thanks to dominics' initial push we have finally started with the long-overdue task of documenting Predis using Sphinx. Documentation is being written and integrated into our separate documentation branch, so make sure to open your pull requests against this branch if you plan to contribute.

Phpiredis extension

Thanks to the work of seppo0010 we were able to add the support for a PHP extension to parse the Redis protocol in a more efficient way since Predis v0.7.0, but now that the ownership of the phpiredis repository has been transferred to me I plan to tweak it and add new features from time to time (though the idea is to keep it minimal and simple). Having said that, I am by no means a C developer so help and contributions will be highly welcome and appreciated!

Additional notes

Downloads

v0.8.0

9 years ago

Predis is a flexible and feature-complete PHP (>= 5.3.2) client library for Redis.

This is a major release and it is not backwards compatible with the v0.7.x series due to the fact that some namespaces and classes have been renamed or moved and a few parameters and client options have been modified. What follows is an overview of the new features and major changes introduced with this new release, for a more in-depth list of changes please read the CHANGELOG.

New features and changes

Support for Redis versions and features

The default server profile is now 2.6 which is the current stable branch of Redis while the dev profile targets Redis 2.8. Please note that starting with Redis 2.6 the output of INFO is splitted into sections and, to accomodate this change, Predis returns nested named arrays when using the 2.6 profile.

Connection parameters and client options

There are some changes for connection parameters.

  • connection_async is now async_connect
  • connection_timeout is now timeout
  • connection_persistent is now persistent
  • throw_errors has been removed, replaced by the new exceptions client option.

Please note that using the old parameter names with this new version does not raise any notice.

As an example, the following client configuration for Predis v0.7.x:

$parameters = "tcp://127.0.0.1?connection_async=1&connection_timeout=5&connection_persistent=1&throw_errors=1";
$client = new Predis\Client($parameters);

starting with Predis v0.8.0 must be changed into:

$parameters = "tcp://127.0.0.1?async_connect=1&timeout=5&persistent=1"
$client = new Predis\Client($parameters, array('exceptions' => true));

Additionally, the second parameter of the constructor of Predis\Client does not accept strings or instances of Predis\Profile\ServerProfileInterface like in the past but the server profile must be set by using the profile client option explicitly:

$client = new Predis\Client('tcp://127.0.0.1', '2.4');                      // Wrong
$client = new Predis\Client('tcp://127.0.0.1', array('profile' => '2.4'));  // OK

Redis Cluster

While redis-cluster will not be available until Redis 3.0, Predis already ships with a first working implementation of the logic needed to use this amazing new feature. Configuring the client is simply a matter of passing the list of nodes in the same exact order as they are specified when using redis-trib and setting the cluster client option to redis:

$nodes = array('tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3');
$client = new Predis\Client($nodes, array('cluster' => 'redis'));

Obviously you can rest assured that the good old way of creating a cluster of Redis nodes simply by relying on client-side sharding is still in place and is the default behavior of the client.

Server-side scripting with Lua

Predis supported Redis scripting since v0.7.0 but our high-level abstraction built on top of EVAL and EVALSHA (we call it a scripted command) has been improved to save bandwidth by using the latter by default and falling back transparently to the former when required (that is, when Redis replies to EVALSHA with a -NOSCRIPT error).

Going asynchronous with Predis\Async

Crazy? Maybe, but at least now you can thanks to Predis\Async. This separate project shares the same style and feel of Predis by reusing some of its core classes and is built on top of React to provide a fully-asynchronous implementation of a Redis client. The library is considered experimental and subject to changes in its API, but it already works and can cooperate seamlessy with any other library that makes use of the core event loop abstraction provided by React/EventLoop.

Future development

While this new major release admittedly do not add much features to the plate aside from early support for redis-cluster and a separate project for a fully-asynchronous client, the internals of Predis have been extensively reworked to make the library and its core parts even more easy to extend and reuse, but also with some optimizations put in place. We are at a point in which further changes to the internal architecture of Predis should not be needed for a while, or at least not until we decide to drop compatibility with PHP 5.3 and rewrite stuff to make use of new features introduced in PHP 5.4, which means that we can proceed with experimenting a few ideas such as having core parts of the library implemented in C as an optional PHP extension. Right now you can already use phpiredis to speed thins up, but we can definitely do better that that.

In a more immediate future, aside from addressing eventual bugs the next patch releases in the v0.8.x series will also see the addition of some missing features such as an abstration to deal with redis-sentinel.

Additional notes

Downloads

v0.7.3

9 years ago

Predis is a flexible and feature-complete PHP client library for Redis.

This is a maintenance release for the 0.7 series. What follows is an overview of the new features introduced in this new release. For a more in-depth list of changes please see the CHANGELOG.

New features and changes

New commands in the Redis 2.6 server profile

Two new commands have been added to Redis 2.6: BITOP and BITCOUNT.

Scripting abstraction improvements

It is now possible to use negative numbers in the getKeysCount() method to tell Predis\Commands\ScriptedCommand to calculate the actual number of keys used to populate the KEYS array for EVAL starting from the end of the arguments list. You can read this comment for a description of a use case.

We also fixed a bug in Predis\Commands\ServerEvalSHA::getScriptHash().

Additional notes

Downloads

v0.7.2

9 years ago

Predis is a flexible and feature-complete PHP client library for Redis.

This is a maintenance release for the 0.7 series. What follows is an overview of the new features introduced in this new release. For a more in-depth list of changes please see the CHANGELOG..

New features and changes

New server profile for Redis 2.6

While 2.4 is still the default server profile, you can now use 2.6 instead of dev to use the new commands and features (such as scripting) implemented in Redis 2.6:

$client = new Predis\Client('tcp://127.0.0.1', array('profile' => '2.6'));

The dev profile will target Redis 2.8.

MONITOR and Redis 2.6

The output of MONITOR in Redis 2.6 has been slightly changed resulting in the inability for Predis\MonitorContext to work properly. Now Predis can handle the new output automatically and will add the client field to the returned message object when connected to Redis >= 2.6.

Serializable connections

Connection instances can be serialized and unserialized using serialize() and unserialize(). While probably not useful in most scenarios, this can be handy for example with client-side clustering or replication to lower the overhead of initializing a connection object with many sub-connections since unserializing them can be up to 5x times faster.

$client1 = new Predis\Client();
$serializedConnection = serialize($client->getConnection());

$unserializedConnection = unserialize($serializedConnection);
$client2 = new Predis\Client($unserializedConnection);

Additional notes

Downloads

v0.7.1

9 years ago

Predis is a flexible and feature-complete PHP client library for Redis.

This is a maintenance release for the 0.7 series that fixes some minor glitches and adds a couple of new features. What follows is an overview of the new features introduced in this new release. For a more in-depth list of changes please see the CHANGELOG..

New features and changes

New PEAR channel

We still want to have PEAR as one of the methods to distribute Predis, but unfortunately PearHub seems to be unmaintained and the generation of new PEAR packages is currently stuck. To overcome this issue we set up a new PEAR channel that will host past and future releases of Predis.

Master / slave replication

This one has been a long-standing feature request but master / slave replication configurations are now supported at client level, which means that it is now possible to configure a group of connections with one master server and one or more slave servers. Commands performing read operations (such as GET) are executed against one of the slaves and the client switches to the master only upon commands performing write operations (such as SET). The configuration of a new client instance for replication is easy, just set the replication client option to true and specify at least two connections, with one of them being the master (see alias=master):

$parameters = array(
    'tcp://127.0.0.1:6379?alias=master',
    'tcp://127.0.0.1:6380?alias=slave1',
);

$options = array('replication' => true);

$client = new Predis\Client($parameters, $options);

Redis transactions (MULTI / EXEC) force the client to switch to the master server even when the transaction contains read-only operations. The same applies to pipelines, but in this case it is is an implementation detail that could change in future releases.

EVAL and EVALSHA are considered write commands by default since it is not possible for the client to know when a script performs read-only operations or not. Developers can still override this behaviour on a script-basis with a slightly more complex configuration using the replication client option:

$options = array(
    'replication' => function() {
        $replication = new Predis\Network\MasterSlaveReplication();
        $replication->setScriptReadOnly("return redis.call('GET', KEYS[1])");

        return $replication;
    },
);

You can see this example for a complete script using a simple configuration and this one for a more complex one.

Additional notes

Downloads

v0.7.0

9 years ago

Predis is a flexible and feature-complete PHP client library for Redis.

This is a major release and it is not backwards compatible with the 0.6 series. Predis requires at least PHP 5.3.2 and works perfectly fine on PHP 5.4-dev. Support for PHP 5.2 has been irrevocably dropped and there will not be any more backported release. What follows is an overview of the new features and changes introduced with this new release. For a more in-depth list of changes please read the CHANGELOG.

New features and changes

PSR-0 autoloading

Predis now adheres to the PSR-0 standard that defines a precise scheme for autoloading widely accepted and used by more and more frameworks and libraries. This means that the times when the library consisted of a mere single file are now gone and you need to use a PSR-0 compatible autoloader to be able to use Predis. Basically any modern framework offers such a facility, but when you are using Predis in simple scripts you can just leverage the default basic autoloader class that comes with Predis by requiring Predis/Autoloader.php followed by Predis\Autoloader::register().

Packagist and Composer

Predis is available on Packagist making the library installable using Composer. This makes things a lot easier when managing dependencies in your applications and libraries. It is still possible to install Predis via PEAR using PearHub's channel.

Support for Redis versions and features

The default server profile is 2.4 which is currently the stable branch of Redis. The dev profile targets Redis 2.6 and supports some new features added to Redis such as server-side scripting with Lua. Support for Redis 1.0 has been completely removed.

Multiple connection backends

The default class responsible for connection and protocol handling is now part of a pluggable system that makes it possible to replace the default implementation with custom ones. For example, it is now possible to leverage the phpiredis C extension to lower the overhead of protocol handling thus gaining speed especially with multibulk replies.

$parameters = 'tcp://127.0.0.1:6379';
$options = array('connections' => array(
    'tcp'  => 'Predis\Network\PhpiredisConnection',
    'unix' => 'Predis\Network\PhpiredisConnection',
));

$client = new Predis\Client($parameters, $options);

This also opens up the possibility of having different classes implementing new kinds of protocols. Now that the redis scheme has been removed in favour of the tcp scheme, you can restore it with the following lines of code:

$parameters = 'redis://127.0.0.1:6379';
$options = array('connections' => array(
    'redis'  => 'Predis\Network\StreamConnection',
));

$client = new Predis\Client($parameters, $options);

Webdis

By leveraging the multiple-backends design for connections, Predis is able to talk with Webdis by default, albeit with certain restrictions since pipelining and transactions are not supported, provided that you are using a PHP interpreter with both the curl and phpiredis extensions loaded. Simply specify the http scheme in your connection parameters and use the client as you would normally do:

$client = new Predis\Client('http://127.0.0.1:7369');

Transparent key prefixing

Predis can now apply a prefix to your keys automatically by specifying a string in the prefix client option. The prefix is applied globally to your client instance which means that it will be used for all the connections that compose a cluster. The standard prefixing strategy is also able to handle commands with a complex use of keys such as SORT.

$client = new Predis\Client('tcp://127.0.0.1:6370', array('prefix' => 'pfx:'));

Future development

Predis v0.7.0 is actually very stable and it is already being used by many developers since a few months without any major issue reported, and recently a whole new comprehensive test suite has been added to ensure this stability. This is also a long overdue release that has been postponed many times in the past for various reasons, but all in all Predis v0.6 served well its purpose (no bugs reported for it since the release of v0.6.6 in April!) so now we can finally have a solid new major release.

There is one missing feature that was initially planned for Predis v0.7.0 but has now been postponed to Predis v0.8: support for redis-cluster. The release plans for redis-cluster changed quite a bit in the last months and it has been pushed back to later dates at least a couple of times. Add to that the fact that this shiny new beast would require some more changes in the internal design of Predis to provide a decent support and you will easily understand the reason for this decision.

Additional notes

Downloads

v0.6.6

9 years ago

Predis is a flexible and feature-complete PHP client library for Redis. This is a maintenance release for the 0.6 series that features mainly performance improvements and adds some new features. As with previous releases, Predis is also available for PHP 5.2 with an officially supported backport (PHP >= 5.2.6). What follows is an overview of the new features introduced in this new release. For a more in-depth list of changes please see the CHANGELOG.

Please read also the roadmap for future releases paragraph.

New features and changes

New default server profile

The default server profile has been upgraded to Redis 2.2 since there are no changes that would break backwards compatibility in your applications. That said, if you are still using Redis 2.0 (or an older version of Redis) but you want to upgrade Predis, it is advisable to set accordingly the server profile that will be used by the client instance.

Long aliases for Redis commands are no more supported by default, but if you need them you can still require Predis_Compatibility.php which will automatically register new server profiles providing them.

Performance improvements

Performances for this release have been further improved resulting in an average 16% faster processing of multi bulk replies and a bit more throughput for pipelined and non-pipelined commands executed against local Redis instances.

A new lightweight response reader that uses less memory and is a bit faster than the previous one is now being used internally but the old handler-based response reader can be enabled by passing composable as the value for the new reader client option:

$client = new Predis\Client($server, array('reader' => 'composable'));

This option can also accept any class implementing the Predis\IResponseReader interface (e.g. Predis\FastResponseReader), which means that developers can create their own response readers.

A few core classes have also been optimized in order to generate less overhead when creating their instances.

UNIX domain sockets

Users can now connect to local Redis instances using UNIX domain sockets on POSIX systems:

$client = new Predis\Client('unix:///tmp/redis.sock');
$client = new Predis\Client(array('scheme' => 'unix', 'path' => '/tmp/redis.sock'));

Redis commands improvements

SINTERSTORE, SUNIONSTORE, SDIFFSTORE, ZINTERSTORE and ZUNIONSTORE can now accept an array to specify the list of the source keys to be used to populate the destination key:

$client->sinterstore('setOutput', array('setA', 'setB'));
$client->zunionstore('zsetOutput', array('zsetA', 'zsetB', 'zsetC'), $options);

The same applies for commands that simply accept a variable number of keys such as MGET, SINTER, SUNION, SDIFF, SUBSCRIBE and PSUBSCRIBE:

$keys = $client->mget(array('key1', 'key2', 'key3'));
$set = $client->sinter(array('setA', 'setB', 'setC'));
$client->subscribe(array('channel1', 'channel2', 'channel3'));

Notes

Roadmap for future releases (Predis v0.7.0)

Predis 0.7 has been in the works for a while now and the first stable release has been delayed a couple of times, but for very good reasons. Right now it is in a kind of beta stage but it is already being leveraged by a few developers in the wild with success. To cite a few points that will make it an exciting major release:

  • It targets only PHP >= 5.3. If you are still on PHP 5.2 then you will have to stick with Predis 0.6, but you should seriously consider to upgrade since PHP 5.2 is slower and it is not even supported anymore.
  • It is faster and consumes less memory than Predis v0.6.6 by default, with options to make it even faster.
  • The internal API is much more clean and coherent, and almost every class used internally by the library can be easily swapped by custom implementations. Almost nothing has changed in the way Redis commands are exposed by the main client class (using them is as easy as it has always been).
  • It complies with PSR-0 to play nice with many recent PHP frameworks such as Symfony2 (see also the excellent RedisBundle project).
  • It will transparently support Redis cluster (when available) as an option to the current cluster implemented via client-side sharding.

You should expect at least one more patch release for Predis 0.6 finalizing a couple of things before Predis v0.7.0 is officially released as stable.

Downloads

  • PHP 5.3 (mainline): TGZ or ZIP
  • PHP 5.2 (backport): TGZ or ZIP

v0.6.5

9 years ago

Predis is a flexible and feature-complete PHP client library for Redis. This is a maintenance release for the 0.6 series exclusively aimed to fix a bug introduced in v0.6.4 when reading zero-length bulk replies from the server. For a complete list of the new features introduced in Predis v0.6.4 you can read the related release notes.

New features and changes

Fix for the zero-length bulk replies bug

Due to a minor change introduced in Predis v0.6.4 that was not covered by any test, zero-length bulk replies were being incorrectly handled, which resulted in protocol desynchronization errors. Here is a snippet to reproduce the issue with v0.6.4:

$redis->set('foo', '');
$foo1 = $redis->get('foo'); // correct value returned, but wrong protocol handling
$foo2 = $redis->get('foo'); // desynchronization error ensues with the successive read op.    

Notes

Credits

Thanks to Jordi Boggiano for quickly spotting the above-mentioned bug and providing a patch to fix the issue.

Downloads

  • PHP 5.3 (mainline): TGZ or ZIP
  • PHP 5.2 (backport): TGZ or ZIP