Compare commits

..

15 Commits

Author SHA1 Message Date
Daniele Alessandri 74cc0e3225 Bump version in files for release. 2012-04-01 10:09:20 +02:00
Daniele Alessandri b5ae1b9a2b Update README. 2012-03-31 11:58:38 +02:00
Daniele Alessandri 31c47362fb Add a couple of paragraphs in the FAQ. 2012-03-31 11:29:59 +02:00
Daniele Alessandri 871f1a3a1d Update TODO. 2012-03-31 10:45:16 +02:00
Daniele Alessandri ba0338e3d8 Update CHANGELOG. 2012-03-31 10:44:29 +02:00
Daniele Alessandri a7c906ab4c Apparently the next major version or Redis will be 2.8. 2012-03-31 10:43:50 +02:00
Daniele Alessandri 7675bb040a Make it possible to prepend the autoloader. 2012-03-19 11:31:39 +01:00
Daniele Alessandri 930af24c7f Make Predis\Autoloader faster. 2012-03-18 18:00:00 +01:00
Daniele Alessandri 23ed563e45 Add missing tests for Predis\Profiles\ServerProfile::defineCommand(). 2012-03-18 12:58:19 +01:00
Daniele Alessandri f00bf6443d Update CHANGELOG.
[ci skip]
2012-03-11 14:01:49 +01:00
Daniele Alessandri 6d73f4a538 Promote 2.6 as an independent server profile for Redis 2.6.
The development server profile now targets Redis 3.0.
2012-03-11 13:53:28 +01:00
Daniele Alessandri f0f3d7814c Fix MONITOR and Predis\MonitorContext with Redis 2.6.
Starting with 2.6, Redis uses a slightly different format for the payload
returned by MONITOR for each command. Predis can now adapt to this difference
and returns a new `client` field in the payload object. This new field is
always defined but is set to NULL when connected to Redis < 2.6.

Please note that Redis 2.6 now does not echo the `MONITOR` command as the
first payload when opening a new MONITOR context.
2012-03-11 13:30:30 +01:00
Daniele Alessandri 5c2704c9d4 Add a not about MONITOR failing the test with Redis unstable. 2012-03-07 13:04:28 +01:00
Daniele Alessandri effefcee34 New command: TIME (Redis v2.6-dev). 2012-03-07 12:30:39 +01:00
Daniele Alessandri 86bf223ec0 Enable integration tests for Redis commands on Travis CI.
This was not possible before since our test suite requires Redis >= 2.4 but
their environment was running Redis 2.2 until a month ago or so.
2012-02-25 11:04:31 +01:00
636 changed files with 17805 additions and 32128 deletions
-17
View File
@@ -1,17 +0,0 @@
# http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
[*.php]
trim_trailing_whitespace = true
max_line_length = 120
[*.{md,yml}]
indent_size = 2
-10
View File
@@ -1,10 +0,0 @@
* text=auto
/tests export-ignore
/.editorconfig export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/.php_cs export-ignore
/.travis.yml export-ignore
/phpunit.xml.dist export-ignore
/phpunit.xml.travisci export-ignore
-4
View File
@@ -1,9 +1,5 @@
*.tgz
*.phar
.php-version
.php_cs.cache
phpunit.xml
package.xml
composer.lock
experiments/
vendor/
-34
View File
@@ -1,34 +0,0 @@
<?php
$PREDIS_HEADER = <<<EOS
This file is part of the Predis package.
(c) Daniele Alessandri <suppakilla@gmail.com>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOS;
Symfony\CS\Fixer\Contrib\HeaderCommentFixer::setHeader($PREDIS_HEADER);
return Symfony\CS\Config\Config::create()
->setUsingCache(true)
->level(Symfony\CS\FixerInterface::SYMFONY_LEVEL)
->fixers(array(
// Symfony
'-unalign_equals',
'-unalign_double_arrow',
// Contribs
'header_comment',
'ordered_use',
'phpdoc_order',
'long_array_syntax',
))
->finder(
Symfony\CS\Finder\DefaultFinder::create()
->in(__DIR__.'/bin')
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
->in(__DIR__.'/examples')
);
+4 -20
View File
@@ -1,25 +1,9 @@
language: php
sudo: false
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
branches:
except:
- v0.5
- v0.6
- php5.2_backport
- documentation
services: redis-server
before_script:
- composer self-update
- composer install --no-interaction --prefer-source --dev
script:
- vendor/bin/phpunit -c phpunit.xml.travisci
matrix:
allow_failures:
- php: hhvm
fast_finish: true
only:
- master
- v0.7
script: phpunit -c phpunit.xml.travisci
+14 -484
View File
@@ -1,475 +1,5 @@
v1.0.2 (2015-07-30)
================================================================================
- IPv6 is now fully supported.
- Added `redis` as an accepted scheme for connection parameters. When using this
scheme, the rules used to parse URI strings match the provisional registration
[published by IANA](http://www.iana.org/assignments/uri-schemes/prov/redis).
- Added new or missing commands: `HSTRLEN` (>= 3.2), `ZREVRANGEBYLEX` (>= 2.8)
and `MIGRATE` (>= 2.6).
- Implemented support for the `ZADD` modifiers `NX|XX`, `CH`, `INCR` (Redis >=
3.0.2) using the simplified signature where scores and members are passed as
a named array.
- __FIX__: `Predis\Configuration\Options` must not trigger the autoloader when
option values are strings (ISSUE #257).
- __FIX__: `BITPOS` was not defined in the key-prefix processor (ISSUE #265) and
in the replication strategy.
v1.0.1 (2015-01-02)
================================================================================
- Added `BITPOS` to the server profile for Redis 2.8.
- Connection timeout for read/write operations can now be set for UNIX sockets
where the underlying connection uses PHP's stream.
- __FIX__: broken values returned by `Predis\Collection\Iterator\SortedSetKey`
when iterating sorted set containing integer members (ISSUE #216).
- __FIX__: applied a minor workaround for a bug in old versions of PHP < 5.3.9
affecting inheritance.
- __FIX__: prevent E_NOTICE warnings when using INFO [section] returns an empty
response due to an unsupported specific set of information requested to Redis.
v1.0.0 (2014-08-01)
================================================================================
- Switched to PSR-4 for autoloading.
- The default server profile for Redis is `3.0`.
- Removed server profile for Redis 1.2.
- Added `SENTINEL` to the profile for Redis 2.6 and `PUBSUB` to the profile for
Redis 2.8.
- `Predis\Client` can now send raw commands using `Predis\Client::executeRaw()`.
- Status responses are returned as instances of `Predis\Response\Status`, for
example +OK is not returned as boolean TRUE anymore which is a breaking change
for those using strict comparisons. Status responses can be casted to string
values carrying the original payload, so one can do `$response == 'OK'` which
is also more akin to how Redis replies to clients.
- Commands `ZRANGE`, `ZRANGEBYSCORE`, `ZREVRANGE` and `ZREVRANGEBYSCORE` using
`WITHSCORE` return a named array of member => score instead of using an array
of [member, score] elements. Insertion order is preserved anyway due to how
PHP works internally.
- The command `ZSCAN` returns a named array of member => score instead of using
an array of [member, score] elements. Insertion order is preserved anyway due
to how PHP works internally.
- The rules for redis-cluster are now leveraged for empty key tags when using
client-side sharding, which means that when one or the first occurrence of {}
is found in a key it will most likely produce a different hash than previous
versions of Predis thus leading to a different partitioning in these cases.
- Invoking `Predis\Client::connect()` when the underlying connection has been
already established does not throw any exception anymore, now the connection
simply does not attempt to perform any operation.
- Added the `aggregate` client option, useful to fully customize how the client
should aggregate multiple connections when an array of connection parameters
is passed to `Predis\Client::__construct()`.
- Dropped support for streamable multibulk responses. Actually we still ship the
iterator response classes just in case anyone would want to build custom stuff
at a level lower than the client abstraction (our standard and composable text
protocol processors still handle them and can be used as an example).
- Simplified the implementation of connection parameters by removing method used
to cast to int / bool / float certain parameters supplied by users. Casting
values, if deemed necessary, should be done by the consumer or you can just
subclass `Predis\Connection\Parameters` and override the `filter()` method.
- Changed a couple of options for our transaction abstraction:
- `exceptions`: overrides the value of the client option with the same name.
Please note that it does not affect all the transaction control commands
such as `MULTI`, `EXEC`, `DISCARD`, `WATCH` and `UNWATCH`.
- `on_retry`: this option has been removed.
- Removed pipeline executors, now command pipelines can be easily customized by
extending the standard `Predis\Pipeline\Pipeline` class. Accepted options when
creating a pipeline using `Predis\Client::pipeline()` are:
- `atomic`: returns a pipeline wrapped in a MULTI / EXEC transaction
(class: `Predis\Pipeline\Atomic`).
- `fire-and-forget`: returns a pipeline that does not read back responses
(class: `Predis\Pipeline\FireAndForget`).
- Renamed the two base abstract command classes:
- `Predis\Command\AbstractCommand` is now `Predis\Command\Command`
- `Predis\Command\ScriptedCommand` is now `Predis\Command\ScriptCommand`
- Dropped `Predis\Command\Command::__toString()` (see issue #151).
- The key prefixing logic has been moved from command classes to the key prefix
processor. Developers can define or override handlers used to prefix keys, but
they can also define the needed logic in their command classes by implementing
`Predis\Command\PrefixableCommandInterface` just like before.
- `Predis\PubSub\DispatcherLoop` now takes a `Predis\PubSub\Consumer` instance
as the sole argument of its constructor instead of `Predis\ClientInterface`.
- All of the interfaces and classes related to translated Redis response types
have been moved in the new `Predis\Response` namespace and most of them have
been renamed to make their fully-qualified name less redundant. Now the base
response interface is `Predis\Response\ResponseInterface`.
- Renamed interface `Predis\Command\Processor\CommandProcessorInterface` to a
shorter `Predis\Command\Processor\ProcessorInterface`. Also removed interface
for chain processors since it is basically useless.
- Renamed `Predis\ExecutableContextInterface` to `Predis\ClientContextInterface`
and augmented it with a couple of required methods since this interface is no
more comparable to a basic client as it could be misleading.
- The `Predis\Option` namespace is now known as `Predis\Configuration` and have
a fully-reworked `Options` class with the ability to lazily initialize values
using objects that responds to `__invoke()` (not all the kinds of callables)
even for custom options defined by the user.
- Renamed `Predis\Connection\ConnectionInterface::writeCommand()` into
`writeRequest()` for consistency with its counterpart, `readResponse()`.
- Renamed `Predis\Connection\SingleConnectionInterface::pushInitCommand()` into
`addConnectCommand()` which is more obvious.
- Renamed the connection class based on both ext-phpiredis and ext-socket into
`Predis\Connection\PhpiredisSocketConnection`. The one based on PHP's streams
is still named `Predis\Connection\PhpiredisStreamConnection`.
- Renamed the connection factory class to `Predis\Connection\Factory`. Now its
constructor does not require anymore a profile instance to create `AUTH` and
`SELECT` commands when parameters contain both `password` and `database`. Raw
commands will be used instead.
- Renamed the connection parameters class to `Predis\Connection\Parameters`. Now
its constructor accepts only named arrays, but instances can still be created
using both URIs or arrays using the static method `Parameters::create()`.
- The profile factory code has been extracted from the abstract Redis profile
class and now lives in `Predis\Profile\Factory`.
- The `Predis\Connection` namespace has been completely reorganized by renaming
a few classes and interfaces and adding some sub-namespaces.
- Most classes and interfaces in the `Predis\Protocol` namespace have been moved
or renamed while rationalizing the whole API for external protocol processors.
v0.8.7 (2014-08-01)
================================================================================
- Added `3.0` in the server profiles aliases list for Redis 3.0. `2.8` is still
the default server profile and `dev` still targets Redis 3.0.
- Added `COMMAND` to the server profile for Redis 2.8.
- Switched internally to the `CLUSTER SLOTS` command instead of `CLUSTER NODES`
to fetch the updated slots map from redis-cluster. This change requires users
to upgrade Redis nodes to >= 3.0.0b7.
- The updated slots map is now fetched automatically from redis-cluster upon the
first `-MOVED` response by default. This change makes it possible to feed the
client constructor with only a few nodes of the actual cluster composition,
without needing a more complex configuration.
- Implemented support for `PING` in PUB/SUB loop for Redis >= 3.0.0b8.
- The default client-side sharding strategy and the one for redis-cluster now
share the same implementations as they follow the same rules. One difference,
aside from the different hashing function used to calculate distribution, is
in how empty hash tags like {} are treated by redis-cluster.
- __FIX__: the patch applied to fix #180 introduced a regression affecting read/
write timeouts in `Predis\Connection\PhpiredisStreamConnection`. Unfortunately
the only possible solution requires PHP 5.4+. On PHP 5.3, read/write timeouts
will be ignored from now on.
v0.8.6 (2014-07-15)
================================================================================
- Redis 2.8 is now the default server profile as there are no changes that would
break compatibility with previous releases.
- Added `PFADD`, `PFCOUNT`, `PFMERGE` to the server profile for Redis 2.8 for
handling the HyperLogLog data structure introduced in Redis 2.8.9.
- Added `ZLEXCOUNT`, `ZRANGEBYLEX`, `ZREMRANGEBYLEX` to the server profile for
Redis 2.8 for handling lexicographic operations on members of sorted sets.
- Added support for key hash tags when using redis-cluster (Redis 3.0.0b1).
- __FIX__: minor tweaks to make Predis compatible with HHVM >= 2.4.0.
- __FIX__: responses to `INFO` are now properly parsed and will not break when
redis sentinel is being used (ISSUE #154).
- __FIX__: added missing support for `INCRBYFLOAT` in cluster and replication
configurations (ISSUE #159).
- __FIX__: fix parsing of the output of `CLUSTER NODES` to fetch the slots map
from a node when redis-cluster has slaves in its configuration (ISSUE #165).
- __FIX__: prevent a stack overflow when iterating over large Redis collections
using our abstraction for cursor-based iterators (ISSUE #182).
- __FIX__: properly discards transactions when the server immediately returns an
error response (e.g. -OOM or -ERR on invalid arguments for a command) instead
of a +QUEUED response (ISSUE #187).
- Upgraded to PHPUnit 4.* for the test suite.
v0.8.5 (2014-01-16)
================================================================================
- Added `2.8` in the server profiles aliases list for Redis 2.8. `2.6` is still
the default server profile and `dev` now targets Redis 3.0.
- Added `SCAN`, `SSCAN`, `ZSCAN`, `HSCAN` to the server profile for Redis 2.8.
- Implemented PHP iterators for incremental iterations over Redis collections:
- keyspace (cursor-based iterator using `SCAN`)
- sets (cursor-based iterator using `SSCAN`)
- sorted sets (cursor-based iterator using `ZSCAN`)
- hashes (cursor-based iterator using `HSCAN`)
- lists (plain iterator using `LRANGE`)
- It is now possible to execute "raw commands" using `Predis\Command\RawCommand`
and a variable list of command arguments. Input arguments are not filtered and
responses are not parsed, which means arguments must follow the signature of
the command as defined by Redis and complex responses are left untouched.
- URI parsing for connection parameters has been improved and has slightly less
overhead when the number of fields in the querystring grows. New features are:
- Parsing does not break when value of a field contains one or more "=".
- Repeated fieldnames using [] produce an array of values.
- Empty or incomplete "key=value" pairs result in an empty string for "key".
- Various improvements and fixes to the redis-cluster connection backend:
- __FIX__: the `ASKING` command is sent upon -ASK redirections.
- An updated slots-map can be fetched from nodes using the `CLUSTER NODES`
command. By default this is a manual operation but can be enabled to get
automatically done upon -MOVED redirections.
- It is possible to specify a common set of connection parameters that are
applied to connections created on the fly upon redirections to nodes not
part of the initial pool.
- List of deprecated methods:
- `Predis\Client::multiExec()`: superseded by `Predis\Client::transaction()`
and to be removed in the next major release.
- `Predis\Client::pubSub()`: superseded by `Predis\Client::pubSubLoop()` and
to be removed in the next major release. This change was needed due to the
recently introduced `PUBSUB` command in Redis 2.8.
v0.8.4 (2013-07-27)
================================================================================
- Added `DUMP` and `RESTORE` to the server profile for Redis 2.6.
- Connection exceptions now report basic host details in their messages.
- Allow `Predis\Connection\PhpiredisConnection` to use a random IP when a host
actually has several IPs (ISSUE #116).
- __FIX__: allow `HMSET` when using a cluster of Redis nodes with client-side
sharding or redis-cluster (ISSUE #106).
- __FIX__: set `WITHSCORES` modifer for `ZRANGE`, `ZREVRANGE`, `ZRANGEBYSCORE`
and `ZREVRANGEBYSCORE` only when the options array passed to these commands
has `WITHSCORES` set to `true` (ISSUE #107).
- __FIX__: scripted commands falling back from `EVALSHA` to `EVAL` resulted in
PHP errors when using a prefixed client (ISSUE #109).
- __FIX__: `Predis\PubSub\DispatcherLoop` now works properly when using key
prefixing (ISSUE #114).
v0.8.3 (2013-02-18)
================================================================================
- Added `CLIENT SETNAME` and `CLIENT GETNAME` (ISSUE #102).
- Implemented the `Predis\Connection\PhpiredisStreamConnection` class using the
`phpiredis` extension like `Predis\Connection\PhpiredisStreamConnection`, but
without requiring the `socket` extension since it relies on PHP's streams.
- Added support for the TCP_NODELAY flag via the `tcp_nodelay` parameter for
stream-based connections, namely `Predis\Connection\StreamConnection` and
`Predis\Connection\PhpiredisStreamConnection` (requires PHP >= 5.4.0).
- Updated the aggregated connection class for redis-cluster to work with 16384
hash slots instead of 4096 to reflect the recent change from redis unstable
([see this commit](https://github.com/antirez/redis/commit/ebd666d)).
- The constructor of `Predis\Client` now accepts a callable as first argument
returning `Predis\Connection\ConnectionInterface`. Users can create their
own self-contained strategies to create and set up the underlying connection.
- Users should return `0` from `Predis\Command\ScriptedCommand::getKeysCount()`
instead of `FALSE` to indicate that all of the arguments of a Lua script must
be used to populate `ARGV[]`. This does not represent a breaking change.
- The `Predis\Helpers` class has been deprecated and it will be removed in
future releases.
v0.8.2 (2013-02-03)
================================================================================
- Added `Predis\Session\SessionHandler` to make it easy to store PHP sessions
on Redis using Predis. Please note that this class needs either PHP >= 5.4.0
or a polyfill for PHP's `SessionHandlerInterface`.
- Added the ability to get the default value of a client option directly from
`Predis\Option\ClientOption` using the `getDefault()` method by passing the
option name or its instance.
- __FIX__: the standard pipeline executor was not using the response parser
methods associated to commands to process raw responses (ISSUE #101).
v0.8.1 (2013-01-19)
================================================================================
- The `connections` client option can now accept a callable object returning
an instance of `Predis\Connection\ConnectionFactoryInterface`.
- Client options accepting callable objects as factories now pass their actual
instance to the callable as the second argument.
- `Predis\Command\Processor\KeyPrefixProcessor` can now be directly casted to
string to obtain the current prefix, useful with string interpolation.
- Added an optional callable argument to `Predis\Cluster\Distribution\HashRing`
and `Predis\Cluster\Distribution\KetamaPureRing` constructor that can be used
to customize how the distributor should extract the connection hash when
initializing the nodes distribution (ISSUE #36).
- Correctly handle `TTL` and `PTTL` returning -2 on non existing keys starting
with Redis 2.8.
- __FIX__: a missing use directive in `Predis\Transaction\MultiExecContext`
caused PHP errors when Redis did not return `+QUEUED` replies to commands
when inside a MULTI / EXEC context.
- __FIX__: the `parseResponse()` method implemented for a scripted command was
ignored when retrying to execute a Lua script by falling back to `EVAL` after
a `-NOSCRIPT` error (ISSUE #94).
- __FIX__: when subclassing `Predis\Client` the `getClientFor()` method returns
a new instance of the subclass instead of a new instance of `Predis\Client`.
v0.8.0 (2012-10-23)
================================================================================
- The default server profile for Redis is now `2.6`.
- Certain connection parameters have been renamed:
- `connection_async` is now `async_connect`
- `connection_timeout` is now `timeout`
- `connection_persistent` is now `persistent`
- The `throw_errors` connection parameter has been removed and replaced by the
new `exceptions` client option since exceptions on `-ERR` replies returned by
Redis are not generated by connection classes anymore but instead are thrown
by the client class and other abstractions such as pipeline contexts.
- Added smart support for redis-cluster (Redis v3.0) in addition to the usual
cluster implementation that uses client-side sharding.
- Various namespaces and classes have been renamed to follow rules inspired by
the Symfony2 naming conventions.
- The second argument of the constructor of `Predis\Client` does not accept
strings or instances of `Predis\Profile\ServerProfileInterface` anymore.
To specify a server profile you must explicitly set `profile` in the array
of client options.
- `Predis\Command\ScriptedCommand` internally relies on `EVALSHA` instead of
`EVAL` thus avoiding to send Lua scripts bodies on each request. The client
automatically resends the command falling back to `EVAL` when Redis returns a
`-NOSCRIPT` error. Automatic fallback to `EVAL` does not work with pipelines,
inside a `MULTI / EXEC` context or with plain `EVALSHA` commands.
- Complex responses are no more parsed by connection classes as they must be
processed by consumer classes using the handler associated to the issued
command. This means that executing commands directly on connections only
returns simple Redis types, but nothing changes when using `Predis\Client`
or the provided abstractions for pipelines and transactions.
- Iterators for multi-bulk replies now skip the response parsing method of the
command that generated the response and are passed directly to user code.
Pipeline and transaction objects still consume automatically iterators.
- Cluster and replication connections now extend a new common interface,
`Predis\Connection\AggregatedConnectionInterface`.
- `Predis\Connection\MasterSlaveReplication` now uses an external strategy
class to handle the logic for checking readable / writable commands and Lua
scripts.
- Command pipelines have been optimized for both speed and code cleanness, but
at the cost of bringing a breaking change in the signature of the interface
for pipeline executors.
- Added a new pipeline executor that sends commands wrapped in a MULTI / EXEC
context to make the execution atomic: if a pipeline fails at a certain point
then the whole pipeline is discarded.
- The key-hashing mechanism for commands is now handled externally and is no
more a competence of each command class. This change is neeeded to support
both client-side sharding and Redis cluster.
- `Predis\Options\Option` is now abstract, see `Predis\Option\AbstractOption`.
v0.7.3 (2012-06-01)
================================================================================
- New commands available in the Redis v2.6 profile (dev): `BITOP`, `BITCOUNT`.
- When the number of keys `Predis\Commands\ScriptedCommand` is negative, Predis
will count from the end of the arguments list to calculate the actual number
of keys that will be interpreted as elements for `KEYS` by the underlying
`EVAL` command.
- __FIX__: `examples\CustomDistributionStrategy.php` had a mistyped constructor
call and produced a bad distribution due to an error as pointed in ISSUE #63.
This bug is limited to the above mentioned example and does not affect the
classes implemented in the `Predis\Distribution` namespace.
- __FIX__: `Predis\Commands\ServerEvalSHA::getScriptHash()` was calculating the
hash while it just needs to return the first argument of the command.
- __FIX__: `Predis\Autoloader` has been modified to allow cascading autoloaders
for the `Predis` namespace.
v0.7.2 (2012-04-01)
================================================================================
===============================================================================
- Added `2.6` in the server profiles aliases list for the upcoming Redis 2.6.
`2.4` is still the default server profile. `dev` now targets Redis 2.8.
@@ -487,7 +17,7 @@ v0.7.2 (2012-04-01)
v0.7.1 (2011-12-27)
================================================================================
===============================================================================
- The PEAR channel on PearHub has been deprecated in favour of `pear.nrk.io`.
@@ -506,7 +36,7 @@ v0.7.1 (2011-12-27)
v0.7.0 (2011-12-11)
================================================================================
===============================================================================
- Predis now adheres to the PSR-0 standard which means that there is no more a
single file holding all the classes of the library, but multiple files (one
@@ -580,7 +110,7 @@ v0.7.0 (2011-12-11)
v0.6.6 (2011-04-01)
================================================================================
===============================================================================
- Switched to Redis 2.2 as the default server profile (there are no changes
that would break compatibility with previous releases). Long command names
@@ -619,7 +149,7 @@ v0.6.6 (2011-04-01)
v0.6.5 (2011-02-12)
================================================================================
===============================================================================
- __FIX__: due to an untested internal change introduced in v0.6.4, a wrong
handling of bulk reads of zero-length values was producing protocol
@@ -627,7 +157,7 @@ v0.6.5 (2011-02-12)
v0.6.4 (2011-02-12)
================================================================================
===============================================================================
- Various performance improvements (15% ~ 25%) especially when dealing with
long multibulk replies or when using clustered connections.
@@ -641,7 +171,7 @@ v0.6.4 (2011-02-12)
v0.6.3 (2011-01-01)
================================================================================
===============================================================================
- New commands available in the Redis v2.2 profile (dev):
- Strings: `SETRANGE`, `GETRANGE`, `SETBIT`, `GETBIT`
@@ -655,7 +185,7 @@ v0.6.3 (2011-01-01)
v0.6.2 (2010-11-28)
================================================================================
===============================================================================
- Minor internal improvements and clean ups.
@@ -680,7 +210,7 @@ v0.6.2 (2010-11-28)
v0.6.1 (2010-07-11)
================================================================================
===============================================================================
- Minor internal improvements and clean ups.
@@ -722,7 +252,7 @@ v0.6.1 (2010-07-11)
v0.6.0 (2010-05-24)
================================================================================
===============================================================================
- Switched to the new multi-bulk request protocol for all of the commands
in the Redis 1.2 and Redis 2.0 profiles. Inline and bulk requests are now
@@ -734,7 +264,7 @@ v0.6.0 (2010-05-24)
to instances of Redis 1.2.x).
- Support for Redis 1.0 is now optional and it is provided by requiring
'Predis_Compatibility.php' before creating an instance of `Predis\Client`.
'Predis_Compatibility.php' before creating an instance of Predis\Client.
- New commands added to the Redis 2.0 profile since Predis 0.5.1:
- Strings: `SETEX`, `APPEND`, `SUBSTR`
@@ -747,7 +277,7 @@ v0.6.0 (2010-05-24)
- Introduced client-level options with the new `Predis\ClientOptions` class.
Options can be passed to the constructor of `Predis\Client` in its second
argument as an array or an instance of `Predis\ClientOptions`. For brevity's
argument as an array or an instance of Predis\ClientOptions. For brevity's
sake and compatibility with older versions, the constructor still accepts
an instance of `Predis\RedisServerProfile` in its second argument. The
currently supported client options are:
@@ -837,7 +367,7 @@ v0.6.0 (2010-05-24)
v0.5.1 (2010-01-23)
================================================================================
===============================================================================
* `RPOPLPUSH` has been changed from bulk command to inline command in Redis
1.2.1, so `ListPopLastPushHead` now extends `InlineCommand`. The old behavior
@@ -852,5 +382,5 @@ v0.5.1 (2010-01-23)
v0.5.0 (2010-01-09)
================================================================================
===============================================================================
* First versioned release of Predis
-44
View File
@@ -1,44 +0,0 @@
## Filing bug reports ##
Bugs or feature requests can be posted on the [GitHub issues](http://github.com/nrk/predis/issues)
section of the project.
When reporting bugs, in addition to the obvious description of your issue you __must__ always provide
some essential information about your environment such as:
1. version of Predis (check the `VERSION` file or the `Predis\Client::VERSION` constant).
2. version of Redis (check `redis_version` returned by [`INFO`](http://redis.io/commands/info)).
3. version of PHP.
4. name and version of the operating system.
5. when possible, a small snippet of code that reproduces the issue.
__Think about it__: we do not have a crystal ball and cannot predict things or peer into the unknown
so please provide as much details as possible to help us isolating issues and fix them.
__Never__ use GitHub issues to post generic questions about Predis! When you have questions about
how Predis works or how it can be used, please just hop me an email and I will get back to you as
soon as possible.
## Contributing code ##
If you want to work on Predis, it is highly recommended that you first run the test suite in order
to check that everything is OK and report strange behaviours or bugs. When modifying Predis please
make sure that no warnings or notices are emitted by PHP running the interpreter in your development
environment with the `error_reporting` variable set to `E_ALL | E_STRICT`.
The recommended way to contribute to Predis is to fork the project on GitHub, create topic branches
on your newly created repository to fix bugs or add new features (possibly with tests covering your
modifications) and then open a pull request with a description of the applied changes. Obviously you
can use any other Git hosting provider of your preference.
We always aim for consistency in our code base so you should follow basic coding rules as defined by
[PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)
and [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
and stick with the conventions used in Predis to name classes and interfaces. Indentation should be
done with 4 spaces and code should be wrapped at 100 columns (please try to stay within this limit
even if the above mentioned official coding guidelines set the soft limit to 120 columns).
Please follow these [commit guidelines](http://git-scm.com/book/ch5-2.html#Commit-Guidelines) when
committing your code to Git and always write a meaningful (not necessarily extended) description of
your changes before opening pull requests.
+79
View File
@@ -0,0 +1,79 @@
# Some frequently asked questions about the performances of Predis #
____________________________________________
### Predis is a pure-PHP implementation: it can not be fast enough! ###
It really depends, but most of the times the answer is: _yes, it is fast enough_. I will give you
a couple of easy numbers using a single Predis client with PHP 5.3.5 (custom build) and Redis 2.2
(localhost) under Ubuntu 11.04 (running on a Intel Q6600):
19600 SET/sec using 12 bytes for both key and value
18900 GET/sec while retrieving the very same values
0.200 seconds to fetch 30000 keys using _KEYS *_.
How does it compare with a nice C-based extension such as [__phpredis__](http://github.com/nicolasff/phpredis)?
30500 SET/sec using 12 bytes for both key and value
31000 GET/sec while retrieving the very same values
0.030 seconds to fetch 30000 keys using "KEYS *"".
Wow, __phpredis__ looks so much faster! Well we are comparing a C extension with a pure-PHP library so
lower numbers are quite expected, but there is a fundamental flaw in them: is this really how you are
going to use Redis in your application? Are you really going to send thousands of commands in a for-loop
for each page request using a single client instance? If so, well I guess you are probably doing something
wrong. Also, if you need to SET or GET multiple keys you should definitely use commands such as MSET and
MGET. You can also use pipelining to get more performances when this technique can be used.
There is one more thing. We have tested the overhead of Predis by connecting on a localhost instance of
Redis, but how these numbers change when we hit the network by connecting to instances of Redis that
reside on other servers?
Using Predis:
3600 SET/sec using 12 bytes for both key and value
3600 GET/sec while retrieving the very same values
0.210 seconds to fetch 30000 keys using "KEYS *".
Using phpredis:
4000 SET/sec using 12 bytes for both key and value
4000 GET/sec while retrieving the very same values
0.051 seconds to fetch 30000 keys using "KEYS *".
There you go, you get almost the same average numbers and the reason is quite simple: network latency
is a real performance killer and you cannot do (almost) anything about that. As a disclaimer, please
remember that we are measuring the overhead of client libraries implementations and the effects of the
network round-trip time, we are not really measuring how fast Redis is. Redis shines the best with
thousands of concurrent clients doing requests! Also, actual performances should be measured according
to how your application will use Redis.
### I am convinced, but performances for multi-bulk replies (e.g. _KEYS *_) are still worse ###
Fair enough, but there is actually an option for you if you need even more speed and it consists on
installing __[phpiredis](http://github.com/seppo0010/phpiredis)__ (note the additional _i_ in the
name) and let Predis using it. __phpiredis__ is a C-based extension that wraps __hiredis__ (the
official Redis C client library) with a thin layer that exposes its features to PHP. You will now
get the benefits of a faster protocol parser just by adding a single line of code in your application:
$client = new Predis\Client('tcp://127.0.0.1', array(
'connections' => array('tcp' => 'Predis\Network\PhpiredisConnection')
));
As simple as it is, nothing will really change in the way you use the library in your application. So,
how fast is it now? There are not much improvements for inline or short bulk replies (e.g. _SET_ or
_GET_), but the speed for parsing multi-bulk replies is now on par with phpredis:
Using Predis with a phpiredis-based connection to fetch 30000 keys using _KEYS *_:
0.031 seconds from a local Redis instance
0.058 seconds from a remote Redis instance
### If I need to install a C extension to get better performances, why not using phpredis? ###
Good question. Generically speaking, if you need absolute uber-speed using localhost instances of Redis
and you do not care about abstractions built around some Redis features such as MULTI / EXEC, or if you
do not need any kind of extensibility or guaranteed backwards compatibility with different versions of
Redis (Predis currently supports from 1.2 up to 2.2, and even the current development version), then
using __phpredis__ can make sense for you. Otherwise, Predis is for you. Using __phpiredis__ gives you
a nice speed bump, but it is not mandatory.
+70 -139
View File
@@ -1,169 +1,100 @@
# Some frequently asked questions about Predis #
________________________________________________
____________________________________________
### What is the point of Predis? ###
The main point of Predis is about offering a highly customizable and extensible client for Redis,
that can be easily extended by developers while still being reasonabily fast. With Predis you can
swap almost any class with your own custom implementation: you can have custom connection classes,
new distribution strategies for client-side sharding, or handlers to replace or add Redis commands.
All of this can be achieved without messing with the source code of the library and directly in your
own application. Given the fast pace at which Redis is developed and adds new features, this can be
a great asset since it allows developers to add new and still missing features or commands or change
the standard behaviour of the library without the need to break dependencies in production code (at
least to some degree).
The main point of Predis is about offering a highly customizable client for Redis that can be easily
extended by developers while still being reasonabily fast. With Predis you can swap almost any class
used internally with your own custom implementation: you can build connection classes, or new
distribution strategies for client-side sharding, or class handlers to replace existing commands or
add new ones. All of this can be achieved without messing with the source code of the library and
directly in your own application. Given the fast pace at which Redis is developed and adds new
features, this can be a great asset that allows you to add new and still missing features or commands,
or change the behaviour of the library without the need to break your dependencies in production code
(well, at least to some degree).
### How about performances? ###
Please refer to the dedicated __FAQ.PERFORMANCES__ file.
### Why PHP 5.3? ###
Seriously, are you still using PHP 5.2 to build new applications? I assume that if you are throwing Redis
in the mix, then you are probably coding something new after all. PHP 5.3 is faster, less memory hungry
and has a few nice features such as namespaces and closures (kind of). More importantly, PHP 5.2 is not
even officially supported anymore (aside from security patches). PHP 5.3 is not the future of PHP, but
its current present. Furthermore, most of the existing frameworks out there are also making the switch
with their respective new major versions. If you still insist on using PHP 5.2, you can get any recent
backported release of Predis 0.6.x, or just use a different library.
### Why so many files for just one library? ###
Before v0.7, Predis used the one-big-file approach to distribute the library. As much as you prefer having
just one file for everything, this kind of solution is actually not that good. Predis now complies with the
[PSR-0](http://groups.google.com/group/php-standards/web/psr-0-final-proposal) standard to play nice with
the major recent frameworks and libraries, so it needs an autoloader function to be defined. If you still
want to have just one file grouping all the classes for whatever reason, then the __bin/create-single-file.php__
script in the repository can generate it for you. There is also the __bin/create-phar.php__ script that
generates a single [Phar archive](http://www.php.net/manual/en/intro.phar.php) of the whole library.
### Does Predis support UNIX domain sockets and persistent connections? ###
Yes. Obviously persistent connections actually work only when using PHP configured as a persistent
process reused by the web server (see [PHP-FPM](http://php-fpm.org)).
Yes. Obviously, persistent connections actually work when using PHP configured as a persistent process that
gets recycled between requests (see [PHP-FPM](http://php-fpm.org/)).
### Does Predis support transparent (de)serialization of values? ###
No and it will not ever do that by default. The reason behind this decision is that serialization is
usually something that developers prefer to customize depending on their needs and can not be easily
generalized when using Redis because of the many possible access patterns for your data. This does
not mean that it is impossible to have such a feature since you can leverage the extensibility of
this library to define your own serialization-aware commands. You can find more details about how to
do that [on this issue](http://github.com/nrk/predis/issues/29#issuecomment-1202624).
No, and it will not ever do that for you by default. The reason behind this decision is that serialization
is usually something that developers prefer to customize depending on their needs and can not be easily
generalized when using Redis because of the many possible access patterns for the data. This does not
mean that it is impossible to have such a feature, you can leverage Predis' extensibility to define your
own serialization-aware commands. See [here](http://github.com/nrk/predis/issues/29#issuecomment-1202624)
for more details on how to implement such a feature with a practical example.
### How can I force Predis to connect to Redis before sending any command? ###
Explicitly connecting to Redis is usually not needed since the client initializes connections lazily
only when they are needed. Admittedly, this behavior can be inconvenient in certain scenarios when
you absolutely need to perform an upfront check to determine if the server is up and running and
eventually catch exceptions on failures. Forcing the client to open the underlying connection can be
done by invoking `Predis\Client::connect()`:
Explicitly connecting to Redis is usually not needed since the client library relies on lazily initialized
connections to the server, but this behavior can be inconvenient in certain scenarios when you absolutely
need to do an upfront check to detect if the server is up and running and eventually catch exceptions on
failures. In this case developers can use `Predis\Client::connect()` to explicitly connect to the server:
```php
```
$client = new Predis\Client();
try {
$client->connect();
} catch (Predis\Connection\ConnectionException $exception) {
}
catch (Predis\Network\ConnectionException $exception) {
// We could not connect to Redis! Your handling code goes here.
}
$client->info();
```
### How Predis abstracts Redis commands? ###
The approach used to implement Redis commands is quite simple: by default each command follows the
same signature as defined on the [Redis documentation](http://redis.io/commands) which makes things
pretty easy if you already know how Redis works or you need to look up how to use certain commands.
Alternatively, variadic commands can accept an array for keys or values (depending on the command)
instead of a list of arguments. Commands such as [`RPUSH`](http://redis.io/commands/rpush) and
[`HMSET`](http://redis.io/commands/hmset) are great examples:
### How Predis implements abstraction of Redis commands? ###
```php
$client->rpush('my:list', 'value1', 'value2', 'value3'); // plain method arguments
$client->rpush('my:list', ['value1', 'value2', 'value3']); // single argument array
$client->hmset('my:hash', 'field1', 'value1', 'field2', 'value2'); // plain method arguments
$client->hmset('my:hash', ['field1'=>'value1', 'field2'=>'value2']); // single named array
```
An exception to this rule is [`SORT`](http://redis.io/commands/sort) for which modifiers are passed
[using a named array](tests/Predis/Command/KeySortTest.php#L54-L75).
# Speaking about performances... #
_________________________________________________
### Predis is a pure-PHP implementation: it can not be fast enough! ###
It really depends, but most of the times the answer is: _yes, it is fast enough_. I will give you a
couple of easy numbers with a simple test that uses a single client and is executed by PHP 5.5.6
against a local instance of Redis 2.8 that runs under Ubuntu 13.10 on a Intel Q6600:
The approach used in Predis to implement the abstraction of Redis commands is quite simple. By default
every command in the library follows exactly the same argument list as defined in the great online
[Redis documentation](http://redis.io/commands) which makes things pretty easy if you already know how
Redis works or if you need to look up how to use certain commands. Alternatively, variadic commands can
accept an array for keys or values (depending on the command) instead of a list of arguments. See for
example how [RPUSH](http://redis.io/commands/rpush) or [HMSET](http://redis.io/commands/hmset) work:
```
21000 SET/sec using 12 bytes for both key and value.
21000 GET/sec while retrieving the very same values.
0.130 seconds to fetch 30000 keys using _KEYS *_.
$client->rpush('my:list', 'value1', 'value2', 'value3'); // values as arguments
$client->rpush('my:list', array('value1', 'value2', 'value3')); // values as single argument array
$client->hmset('my:hash', 'field1', 'value1', 'field2', 'value2'); // values as arguments
$client->hmset('my:hash', array('field1'=>'value1', 'field2'=>'value2'); // values as single named array
```
How does it compare with [__phpredis__](http://github.com/nicolasff/phpredis), a nice C extension
providing an efficient client for Redis?
```
30100 SET/sec using 12 bytes for both key and value
29400 GET/sec while retrieving the very same values
0.035 seconds to fetch 30000 keys using "KEYS *"".
```
Wow __phpredis__ seems much faster! Well, we are comparing a C extension with a pure-PHP library so
lower numbers are quite expected but there is a fundamental flaw in them: is this really how you are
going to use Redis in your application? Are you really going to send thousands of commands using a
for-loop on each page request using a single client instance? If so... well I guess you are probably
doing something wrong. Also, if you need to `SET` or `GET` multiple keys you should definitely use
commands such as `MSET` and `MGET`. You can also use pipelining to get more performances when this
technique can be used.
There is one more thing: we have tested the overhead of Predis by connecting on a localhost instance
of Redis but how these numbers change when we hit the physical network by connecting to remote Redis
instances?
```
Using Predis:
3200 SET/sec using 12 bytes for both key and value
3200 GET/sec while retrieving the very same values
0.132 seconds to fetch 30000 keys using "KEYS *".
Using phpredis:
3500 SET/sec using 12 bytes for both key and value
3500 GET/sec while retrieving the very same values
0.045 seconds to fetch 30000 keys using "KEYS *".
```
There you go, you get almost the same average numbers and the reason is simple: network latency is a
real performance killer and you cannot do (almost) anything about that. As a disclaimer, remember
that we are measuring the overhead of client libraries implementations and the effects of network
round-trip times, so we are not really measuring how fast Redis is. Redis shines best with thousands
of concurrent clients doing requests! Also, actual performances should be measured according to how
your application will use Redis.
### I am convinced, but performances for multi-bulk responses are still worse ###
Fair enough, but there is an option available if you need even more speed and consists on installing
__[phpiredis](http://github.com/nrk/phpiredis)__ (note the additional _i_ in the name) and let the
client use it. __phpiredis__ is another C extension that wraps __hiredis__ (the official C client
library for Redis) with a thin layer exposing its features to PHP. You can then choose between two
different connection classes:
- `Predis\Connection\PhpiredisStreamConnection` (using native PHP streams).
- `Predis\Connection\PhpiredisSocketConnection` (requires `ext-socket`).
You will now get the benefits of a faster protocol serializer and parser just by adding a couple of
lines of code:
```php
$client = new Predis\Client('tcp://127.0.0.1', array(
'connections' => array(
'tcp' => 'Predis\Connection\PhpiredisStreamConnection',
'unix' => 'Predis\Connection\PhpiredisSocketConnection',
),
));
```
Dead simple. Nothing changes in the way you use the library in your application. So how fast is it
our basic benchmark script now? There are not much improvements for inline or short bulk responses
like the ones returned by `SET` and `GET`, but the speed for parsing multi-bulk responses is now on
par with phpredis:
```
Fatching 30000 keys with _KEYS *_ using Predis paired with phpiredis::
0.035 seconds from a local Redis instance
0.047 seconds from a remote Redis instance
```
### If I need an extension to get better performances, why not using phpredis? ###
Good question. Generically speaking if you need absolute uber-speed using Redis on the localhost and
you do not care about abstractions built around some Redis features such as MULTI / EXEC, or if you
do not need any kind of extensibility or guaranteed backwards compatibility with different versions
of Redis (Predis currently supports from 1.2 up to 2.8 and the current development version), then
using __phpredis__ makes absolutely sense. Otherwise, Predis is perfect for the job and by adding
__phpiredis__ you can get a nice speed bump almost for free.
The only exception to this _rule_ is the [SORT](http://redis.io/commands/sort) command for which modifiers are
[passed using a named array](https://github.com/nrk/predis/blob/v0.7.1/tests/Predis/Commands/KeySortTest.php#L56-77).
+1 -1
View File
@@ -1,4 +1,4 @@
Copyright (c) 2009-2015 Daniele Alessandri
Copyright (c) 2009-2012 Daniele Alessandri
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
+138 -325
View File
@@ -1,265 +1,148 @@
# Predis #
[![Latest Stable Version](https://poser.pugx.org/predis/predis/v/stable.png)](https://packagist.org/packages/predis/predis)
[![Total Downloads](https://poser.pugx.org/predis/predis/downloads.png)](https://packagist.org/packages/predis/predis)
[![License](https://poser.pugx.org/predis/predis/license.svg)](https://packagist.org/packages/predis/predis)
[![Build Status](https://travis-ci.org/nrk/predis.svg?branch=v1.0)](https://travis-ci.org/nrk/predis)
[![HHVM Status](http://hhvm.h4cc.de/badge/predis/predis.png)](http://hhvm.h4cc.de/package/predis/predis)
Predis is a flexible and feature-complete PHP (>= 5.3) client library for the Redis key-value store.
Predis is a flexible and feature-complete [Redis](http://redis.io) client library for PHP >= 5.3.
By default this library does not require any additional C extension, but it can be optionally paired
with [phpiredis](https://github.com/nrk/phpiredis) to lower the overhead of serializing and parsing
the [Redis RESP Protocol](http://redis.io/topics/protocol). An asynchronous implementation of Predis
is available through [Predis\Async](https://github.com/nrk/predis-async) (__experimental__).
Predis can be used with [HHVM](http://www.hhvm.com) >= 2.3.0 but there are no guarantees you will
not run into unexpected issues (especially when the JIT compiler is enabled via `Eval.Jit = true`)
due to HHVM being still under heavy development and not yet 100% compatible with the _standard_ PHP.
More details about this project can be found on the [frequently asked questions](FAQ.md) and on the
[wiki](https://github.com/nrk/predis/wiki).
For a list of frequently asked questions about Predis, see the __FAQ__ file in the root of the repository.
For a version compatible with PHP 5.2 you must use the backported version from the latest release in the
0.6.x series. More details are available on the [official wiki](http://wiki.github.com/nrk/predis) of the
project.
## Main features ##
- Support for a wide range of Redis versions (from __2.0__ to __3.0__) using profiles.
- Clustering via client-side sharding using consistent hashing or custom distributors.
- Smart support for [redis-cluster](http://redis.io/topics/cluster-tutorial) (Redis >= 3.0).
- Support for master-slave replication (write operations on master, read operations on slaves).
- Transparent key prefixing for all known Redis commands using a customizable prefixing strategy.
- Command pipelining (works on both single nodes and aggregate connections).
- Abstraction for Redis transactions (Redis >= 2.0) supporting CAS operations (Redis >= 2.2).
- Abstraction for Lua scripting (Redis >= 2.6) with automatic switching between `EVALSHA` or `EVAL`.
- Abstraction for `SCAN`, `SSCAN`, `ZSCAN` and `HSCAN` (Redis >= 2.8) based on PHP iterators.
- Connections to Redis are established lazily by the client upon the first command.
- Support for both TCP/IP and UNIX domain sockets and persistent connections.
- Support for [Webdis](http://webd.is) (requires both `ext-curl` and `ext-phpiredis`).
- Support for custom connection classes for providing different network or protocol backends.
- Flexible system for defining custom commands and server profiles.
- Complete support for Redis from __1.2__ to __2.6__ and unstable versions using different server profiles.
- Client-side sharding with support for consistent hashing or custom distribution strategies.
- Support for master / slave replication configurations (write on master, read from slaves).
- Command pipelining on single and aggregated connections.
- Transparent key prefixing strategy capable of handling any command known that has keys in its arguments.
- Abstraction for Redis transactions (Redis >= 2.0) with support for CAS operations (Redis >= 2.2).
- Connections to Redis instances are automatically and lazily estabilished upon the first call to a command.
- Ability to connect to Redis using TCP/IP or UNIX domain sockets with support for persistent connections.
- Ability to use alternative connection classes to use different types of network or protocol backends.
- Flexible system to define and register your own set of commands or server profiles to client instances.
## How to use Predis ##
Predis is available on [Packagist](http://packagist.org/packages/predis/predis) which allows a quick
_installation_ using [Composer](http://packagist.org/about-composer). Alternatively, the library can
be found on our [own PEAR channel](http://pear.nrk.io) for a more traditional installation via PEAR.
Ultimately, archives of each release are [available on GitHub](https://github.com/nrk/predis/tags).
Predis is available on [Packagist](http://packagist.org/packages/predis/predis) for an easy installation
using [Composer](http://packagist.org/about-composer). Composer helps you manage dependencies for your
projects and libraries without much hassle which makes it the preferred way to get up and running with
new applications. Alternatively, the library is available on our [own PEAR channel](http://pear.nrk.io)
for a more traditional installation via PEAR. Zip and tar.gz archives are also downloadable from GitHub
by browsing the list of [tagged releases](http://github.com/nrk/predis/tags).
### Loading the library ###
Predis relies on the autoloading features of PHP to load its files when needed and complies with the
[PSR-4 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md).
Autoloading is handled automatically when dependencies are managed through Composer, but it is also
possible to leverage its own autoloader in projects or scripts not having any autoload facility:
Predis relies on the autoloading features of PHP to automatically load the needed files and complies
with the [PSR-0 standard](http://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) for
interoperability with most of the major frameworks and libraries. Everything is transparently handled
for you when installing the library using Composer, but you can also leverage its own autoloader class
if you are going to use it in a project or script without any PSR-0 compliant autoloading facility:
```php
// Prepend a base path if Predis is not available in your "include_path".
``` php
<?php
// prepend a base path if Predis is not present in your "include_path".
require 'Predis/Autoloader.php';
Predis\Autoloader::register();
```
It is possible to create a [phar](http://www.php.net/manual/en/intro.phar.php) archive directly from
the repository by launching `bin/create-phar`. The phar contains a stub defining its own autoloader
so you just need to `require()` it to start using the library. Ultimately it is possible to generate
a single big PHP file containing all the source code simply by launching `bin/create-single-file`,
but this practice __is not__ encouraged.
You can create a single [Phar](http://www.php.net/manual/en/intro.phar.php) archive from the repository
just by launching the `bin/create-phar.php` executable script. The generated Phar archive ships with a
stub defining an autoloader function for Predis, so you just need to require the Phar to be able to use
the library.
Alternatively you can generate a single PHP file that holds every class, just like older versions of
Predis, using the `bin/create-single-file.php` executable script. In this way you can load Predis in your
scripts simply by using functions such as `require` and `include`, but this practice is not encouraged.
### Connecting to Redis ###
### Connecting to a local instance of Redis ###
When creating a client instance without passing any connection parameter, Predis assumes `127.0.0.1`
and `6379` as default host and port. The default timeout for the `connect()` operation is 5 seconds:
When connecting to local instance of Redis (`127.0.0.1` on port `6379`), you do not have to specify any
additional parameter to create a new client instance:
```php
$client = new Predis\Client();
$client->set('foo', 'bar');
$value = $client->get('foo');
``` php
<?php
$redis = new Predis\Client();
$redis->set('foo', 'bar');
$value = $redis->get('foo');
```
Connection parameters can be supplied either in the form of URI strings or named arrays. The latter
is the preferred way to supply parameters, but URI strings can be useful when parameters are read
from non-structured or partially-structured sources:
However you can use an URI string or a named array to specify the needed connection parameters:
```php
// Parameters passed using a named array:
$client = new Predis\Client([
``` php
<?php
$redis = new Predis\Client('tcp://10.0.0.1:6379');
// is equivalent to:
$redis = new Predis\Client(array(
'scheme' => 'tcp',
'host' => '10.0.0.1',
'port' => 6379,
]);
// Same set of parameters, passed using an URI string:
$client = new Predis\Client('tcp://10.0.0.1:6379');
));
```
Starting with Predis v1.0.2 the client also understands the `redis` scheme in URI strings as defined
by the [provisional IANA registration](http://www.iana.org/assignments/uri-schemes/prov/redis).
The actual list of supported connection parameters can vary depending on each connection backend so
it is recommended to refer to their specific documentation or implementation for details.
### Pipelining multiple commands to multiple instances of Redis with client-side sharding ###
When an array of connection parameters is provided, Predis automatically works in cluster mode using
client-side sharding. Both named arrays and URI strings can be mixed when providing configurations
for each node:
Pipelining helps with performances when there is the need to send many commands to a server in one go.
Furthermore, pipelining works transparently even on aggregated connections. To achieve this, Predis
supports client-side sharding using consistent-hashing on keys while clustered connections are supported
natively by the client class.
```php
$client = new Predis\Client([
'tcp://10.0.0.1?alias=first-node',
['host' => '10.0.0.2', 'alias' => 'second-node'],
]);
```
``` php
<?php
$redis = new Predis\Client(array(
array('host' => '10.0.0.1', 'port' => 6379),
array('host' => '10.0.0.2', 'port' => 6379)
));
See the [aggregate connections](#aggregate-connections) section of this document for more details.
### Client configuration ###
Various aspects of the client can be configured simply by passing options to the second argument of
`Predis\Client::__construct()`:
```php
$client = new Predis\Client($parameters, ['profile' => '2.8', 'prefix' => 'sample:']);
```
Options are managed through a mini DI-alike container while their values can be lazily initialized
only when needed. This is a list of the options supported by default:
- `profile`: which profile to use in order to match a specific version of Redis.
- `prefix`: a prefix string that is automatically applied to keys found in commands.
- `exceptions`: whether the client should throw or return responses upon Redis errors.
- `connections`: connection backends or a connection factory to be used by the client.
- `cluster`: which backend to use for clustering (`predis`, `redis` or custom configuration).
- `replication`: which backend to use for replication (predis or custom configuration).
- `aggregate`: custom connections aggregator (overrides both `cluster` and `replication`).
Users can provide custom options with their values or lazy callable initializers that are stored in
the options container for later use through the library.
### Aggregate connections ###
Predis is able to aggregate multiple connections which is the base for clustering and replication.
By default the client implements a cluster of nodes using either client-side sharding (default) or
a Redis-backed solution using [redis-cluster](http://redis.io/topics/cluster-tutorial).
As for replication, Predis can handle a single-master and multiple-slaves setup by executing read
operations on slaves and switching to the master only for write operations. The replication behavior
is fully configurable.
#### Replication ####
The client can be configured to operate in a master-slave setup by executing read-only commands on
slave nodes and automatically switch to the master node as soon as it detects a command that will
perform a write operation. This is the basic configuration needed to work with replication:
```php
// Parameters require one master node specifically marked with `alias=master`.
$parameters = ['tcp://10.0.0.1?alias=master', 'tcp://10.0.0.2?alias=slave-01'];
$options = ['replication' => true];
$client = new Predis\Client($parameters, $options);
```
While Predis is able to distinguish commands performing write and read-only operations, `EVAL` and
`EVALSHA` represent a corner case in which the client switches to the master node because it cannot
tell when a Lua script is safe to be executed on slaves. While this is indeed the default behavior,
when certain Lua scripts do not perform write operations it is possible to provide an hint to tell
the client to stick with slaves for their execution:
```php
$parameters = ['tcp://10.0.0.1?alias=master', 'tcp://10.0.0.2?alias=slave-01'];
$options = ['replication' => function () {
// Set scripts that won't trigger a switch from a slave to the master node.
$strategy = new Predis\Replication\ReplicationStrategy();
$strategy->setScriptReadOnly($LUA_SCRIPT);
return new Predis\Connection\Aggregate\MasterSlaveReplication($strategy);
}];
$client = new Predis\Client($parameters, $options);
$client->eval($LUA_SCRIPT, 0); // Sticks to slave using `eval`...
$client->evalsha(sha1($LUA_SCRIPT), 0); // ... and `evalsha`, too.
```
The `examples` directory contains two complete scripts showing how replication can be configured for
[basic](examples/replication_simple.php) and [complex](examples/replication_complex.php) scenarios.
#### Cluster ####
Simply passing an array of connection parameters to the client constructor configures Predis to work
in cluster mode using client-side sharding. If you, on the other hand, want to leverage Redis >= 3.0
nodes coordinated by redis-cluster, then the client must be initialized like this:
```php
$parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2'];
$options = ['cluster' => 'redis'];
$client = new Predis\Client($parameters, $options);
```
When using redis-cluster it is not necessary to pass all of the nodes that compose your cluster, you
can specify only a few nodes and the client will automatically fetch the full and updated slots map
directly from Redis by contacting one of the servers.
__NOTE__: our support for redis-cluster does not currently consider master / slave replication but
this feature will be added in a future release of the library.
### Command pipelines ###
Pipelining can help with performances when many commands need to be sent to a server by reducing the
latency introduced by network round-trip timings. Pipelining also works with aggregate connections.
The client can execute the pipeline inside a callable block or return a pipeline instance with the
ability to chain commands thanks to its fluent interface:
```php
// Executes a pipeline inside the given callable block:
$responses = $client->pipeline(function ($pipe) {
$replies = $redis->pipeline(function($pipe) {
for ($i = 0; $i < 1000; $i++) {
$pipe->set("key:$i", str_pad($i, 4, '0', 0));
$pipe->get("key:$i");
}
});
// Returns a pipeline that can be chained thanks to its fluent interface:
$responses = $client->pipeline()->set('foo', 'bar')->get('foo')->execute();
```
### Transactions ###
### Overriding standard connection classes with custom ones ###
The client provides an abstraction for Redis transactions based on `MULTI` and `EXEC` with a similar
interface to command pipelines:
Predis allows developers to create new connection classes to add support for new protocols or override
the existing ones and provide a different implementation compared to the default classes. This can be
obtained by subclassing the `Predis\Network\IConnectionSingle` interface.
```php
// Executes a transaction inside the given callable block:
$responses = $client->transaction(function ($tx) {
$tx->set('foo', 'bar');
$tx->get('foo');
});
``` php
<?php
class MyConnectionClass implements Predis\Network\IConnectionSingle
{
// implementation goes here
}
// Returns a transaction that can be chained thanks to its fluent interface:
$responses = $client->transaction()->set('foo', 'bar')->get('foo')->execute();
// Let Predis automatically use your own class to handle connections identified by the tcp scheme.
$client = new Predis\Client('tcp://127.0.0.1', array(
'connections' => array('tcp' => 'MyConnectionClass')
));
```
This abstraction can perform check-and-set operations thanks to `WATCH` and `UNWATCH` and provides
automatic retries of transactions aborted by Redis when `WATCH`ed keys are touched. For an example
of a transaction using CAS you can see [the following example](examples/transaction_using_cas.php).
The classes contained in the `Predis\Network` namespace give you a better insight with actual code on
how to create new connection classes.
### Adding new commands ###
### Defining and registering new commands on the client at runtime ###
While we try to update Predis to stay up to date with all the commands available in Redis, you might
prefer to stick with an old version of the library or provide a different way to filter arguments or
parse responses for specific commands. To achieve that, Predis provides the ability to implement new
command classes to define or override commands in the default server profiles used by the client:
Let's suppose Redis just added the support for a brand new feature associated with a new command. If
you want to start using the above mentioned new feature right away without messing with Predis source
code or waiting for it to find its way into a stable Predis release, then you can start off by creating
a new class that matches the command type and its behaviour and then bind it to a client instance at
runtime. Actually, it is easier done than said:
```php
// Define a new command by extending Predis\Command\Command:
class BrandNewRedisCommand extends Predis\Command\Command
``` php
<?php
class BrandNewRedisCommand extends Predis\Commands\Command
{
public function getId()
{
@@ -267,143 +150,73 @@ class BrandNewRedisCommand extends Predis\Command\Command
}
}
// Inject your command in the current profile:
$client = new Predis\Client();
$client->getProfile()->defineCommand('newcmd', 'BrandNewRedisCommand');
$response = $client->newcmd();
```
There is also a method to send raw commands without filtering their arguments or parsing responses.
Users must provide the list of arguments for the command as an array, following the signatures as
defined by the [Redis documentation for commands](http://redis.io/commands):
```php
$response = $client->executeRaw(['SET', 'foo', 'bar']);
$redis = new Predis\Client();
$redis->getProfile()->defineCommand('newcmd', 'BrandNewRedisCommand');
$redis->newcmd();
```
### Script commands ###
## Test suite ##
While it is possible to leverage [Lua scripting](http://redis.io/commands/eval) on Redis 2.6+ using
[`EVAL`](http://redis.io/commands/eval) and [`EVALSHA`](http://redis.io/commands/evalsha) directly,
Predis offers script commands as an higher level abstraction built upon them to make things simple.
Script commands can be registered in the server profile used by the client and are accessible as if
they were plain Redis commands, but they define Lua scripts that get transmitted to the server for
remote execution. Internally they use [`EVALSHA`](http://redis.io/commands/evalsha) by default and
identify a script by its SHA1 hash to save bandwidth, but [`EVAL`](http://redis.io/commands/eval)
is used as a fall back when needed:
__ATTENTION__: Do not ever run the test suite shipped with Predis against instances of Redis running in
production environments or containing data you are interested in!
```php
// Define a new script command by extending Predis\Command\ScriptCommand:
class ListPushRandomValue extends Predis\Command\ScriptCommand
{
public function getKeysCount()
{
return 1;
}
Predis has a comprehensive test suite covering every aspect of the library. The suite performs integration
tests against a running instance of Redis (>= 2.4.0 is required) to verify the correct behaviour of the
implementation of each command and automatically skips commands not defined in the selected version of
Redis. If you do not have Redis up and running, integration tests can be disabled. By default, the test
suite is configured to execute integration tests using the server profile for Redis v2.4 (which is the
current stable version of Redis). You can optionally run the suite against a Redis instance built from
the `unstable` branch with the development profile by changing the `REDIS_SERVER_VERSION` to `dev` in
the `phpunit.xml` file. More details about testing Predis are available in `tests/README.md`.
public function getScript()
{
return <<<LUA
math.randomseed(ARGV[1])
local rnd = tostring(math.random())
redis.call('lpush', KEYS[1], rnd)
return rnd
LUA;
}
}
// Inject the script command in the current profile:
$client = new Predis\Client();
$client->getProfile()->defineCommand('lpushrand', 'ListPushRandomValue');
$response = $client->lpushrand('random_values', $seed = mt_rand());
```
Predis uses Travis CI for continuous integration. You can find the results of the test suite and the build
history [on its project page](http://travis-ci.org/nrk/predis).
### Customizable connection backends ###
## Contributing ##
Predis can use different connection backends to connect to Redis. Two of them leverage a third party
extension such as [phpiredis](https://github.com/nrk/phpiredis) resulting in major performance gains
especially when dealing with big multibulk responses. While one is based on PHP streams, the other
is based on socket resources provided by `ext-socket`. Both support TCP/IP and UNIX domain sockets:
If you want to work on Predis, it is highly recommended that you first run the test suite in order to
check that everything is OK, and report strange behaviours or bugs. When modifying Predis please make
sure that no warnings or notices are emitted by PHP by running the interpreter in your development
environment with the `error_reporting` variable set to `E_ALL | E_STRICT`.
```php
$client = new Predis\Client('tcp://127.0.0.1', [
'connections' => [
'tcp' => 'Predis\Connection\PhpiredisStreamConnection', // PHP stream resources
'unix' => 'Predis\Connection\PhpiredisSocketConnection', // ext-socket resources
],
]);
```
Developers can create their own connection classes to support whole new network backends, extend
existing classes or provide completely different implementations. Connection classes must implement
`Predis\Connection\NodeConnectionInterface` or extend `Predis\Connection\AbstractConnection`:
```php
class MyConnectionClass implements Predis\Connection\NodeConnectionInterface
{
// Implementation goes here...
}
// Use MyConnectionClass to handle connections for the `tcp` scheme:
$client = new Predis\Client('tcp://127.0.0.1', [
'connections' => ['tcp' => 'MyConnectionClass'],
]);
```
For a more in-depth insight on how to create new connection backends you can refer to the actual
implementation of the standard connection classes available in the `Predis\Connection` namespace.
The recommended way to contribute to Predis is to fork the project on GitHub, create new topic branches
on your newly created repository to fix or add features (possibly with tests covering your modifications)
and then open a new pull request with a description of the applied changes. Obviously you can use any
other Git hosting provider of your preference.
## Development ##
## Dependencies ##
- PHP >= 5.3.2
- PHPUnit >= 3.5.0 (needed to run the test suite)
### Reporting bugs and contributing code ###
## Links ##
Contributions to Predis are highly appreciated either in the form of pull requests for new features,
bug fixes, or just bug reports. We only ask you to adhere to a [basic set of rules](CONTRIBUTING.md)
before submitting your changes or filing bugs on the issue tracker to make it easier for everyone to
stay consistent while working on the project.
### Test suite ###
__ATTENTION__: Do not ever run the test suite shipped with Predis against instances of Redis running
in production environments or containing data you are interested in!
Predis has a comprehensive test suite covering every aspect of the library. This test suite performs
integration tests against a running instance of Redis (>= 2.4.0 is required) to verify the correct
behavior of the implementation of each command and automatically skips commands not defined in the
specified Redis profile. If you do not have Redis up and running, integration tests can be disabled.
By default the test suite is configured to execute integration tests using the profile for Redis 2.8
(which is the current stable version of Redis) but can optionally target a Redis instance built from
the `unstable` branch by modifying `phpunit.xml` and setting `REDIS_SERVER_VERSION` to `dev` so that
the development server profile will be used. You can refer to [the tests README](tests/README.md)
for more detailed information about testing Predis.
Predis uses Travis CI for continuous integration and the history for past and current builds can be
found [on its project page](http://travis-ci.org/nrk/predis).
## Other ##
### Project related links ###
- [Source code](https://github.com/nrk/predis)
- [Wiki](https://wiki.github.com/nrk/predis)
- [Issue tracker](https://github.com/nrk/predis/issues)
### Project ###
- [Source code](http://github.com/nrk/predis/)
- [Wiki](http://wiki.github.com/nrk/predis/)
- [Issue tracker](http://github.com/nrk/predis/issues)
- [PEAR channel](http://pear.nrk.io)
### Related ###
- [Redis](http://redis.io/)
- [PHP](http://php.net/)
- [PHPUnit](http://www.phpunit.de/)
- [Git](http://git-scm.com/)
### Author ###
## Author ##
- [Daniele Alessandri](mailto:suppakilla@gmail.com) ([twitter](http://twitter.com/JoL1hAHN))
## Contributors ##
### License ###
- [Lorenzo Castelli](http://github.com/lcastelli)
- [Jordi Boggiano](http://github.com/Seldaek) ([twitter](http://twitter.com/seldaek))
- [Sebastian Waisbrot](http://github.com/seppo0010) ([twitter](http://twitter.com/seppo0010))
for his work on extending [phpiredis](http://github.com/seppo0010/phpiredis) for Predis
The code for Predis is distributed under the terms of the MIT license (see [LICENSE](LICENSE)).
## License ##
The code for Predis is distributed under the terms of the MIT license (see LICENSE).
+2
View File
@@ -0,0 +1,2 @@
* Documentation! The README is obviously not enought to show how to use Predis
as it does not cover all of its features.
+1 -1
View File
@@ -1 +1 @@
1.0.2
0.7.2
+1 -1
View File
@@ -9,6 +9,6 @@
* file that was distributed with this source code.
*/
require __DIR__.'/src/Autoloader.php';
require __DIR__.'/lib/Predis/Autoloader.php';
Predis\Autoloader::register();
-233
View File
@@ -1,233 +0,0 @@
#!/usr/bin/env php
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// -------------------------------------------------------------------------- //
// In order to be able to execute this script to create a PEAR package of Predis
// the `pear` binary must be available and executable in your $PATH.
// The parts used to parse author and version strings are taken from Onion (used
// by this library in the past) just to keep on relying on the package.ini file
// to simplify things. We might consider to switch to using the PEAR classes
// directly in the future.
// -------------------------------------------------------------------------- //
function executeWithBackup($file, $callback)
{
$exception = null;
$backup = "$file.backup";
copy($file, $backup);
try {
call_user_func($callback, $file);
} catch (Exception $exception) {
// NOOP
}
unlink($file);
rename($backup, $file);
if ($exception) {
throw $exception;
}
}
function parseAuthor($string)
{
$author = array();
if (preg_match('/^\s*(.+?)\s*(?:"(\S+)"\s*)?<(\S+)>\s*$/x', $string , $regs)) {
if (count($regs) == 4) {
list($_,$name,$user,$email) = $regs;
$author['name'] = $name;
$author['user'] = $user;
$author['email'] = $email;
} elseif (count($regs) == 3) {
list($_,$name,$email) = $regs;
$author['name'] = $name;
$author['email'] = $email;
}
} else {
$author['name'] = $string;
}
return $author;
}
function parseVersion($string)
{
$version_pattern = '([0-9.]+)';
if (preg_match("/^\s*$version_pattern\s*\$/x", $string, $regs)) {
return array('min' => $regs[1] ?: '0.0.0');
} elseif (preg_match("/^\s*[>=]+\s*$version_pattern\s*\$/x", $string, $regs)) {
return array('min' => $regs[1] ?: '0.0.0');
} elseif (preg_match("/^\s*[<=]+\s*$version_pattern\s*\$/x", $string, $regs)) {
return array('max' => $regs[1]);
} elseif (preg_match("/^\s*$version_pattern\s*<=>\s*$version_pattern\s*\$/x", $string, $regs)) {
return array(
'min' => $regs[1] ?: '0.0.0',
'max' => $regs[2],
);
}
return null;
}
function addRolePath($pkg, $path, $role)
{
if (is_dir($path)) {
$dirRoot = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::SKIP_DOTS);
$dirTree = new RecursiveIteratorIterator($dirRoot, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($dirTree as $fileinfo) {
if ($fileinfo->isFile()) {
addPackageFile($pkg, $fileinfo, $role, $path);
}
}
} else {
foreach (glob($path) as $filename) {
addPackageFile($pkg, new SplFileInfo($filename), $role);
}
}
}
function addPackageFile($pkg, $fileinfo, $role, $baseDir = '')
{
$fileNode = $pkg->contents->dir->addChild('file');
$fileNode->addAttribute('name', $filepath = $fileinfo->getPathname());
$fileNode->addAttribute('role', $role);
$fileNode->addAttribute('md5sum', md5_file($filepath));
$installNode = $pkg->phprelease->filelist->addChild('install');
$installNode->addAttribute('name', $filepath);
$installNode->addAttribute('as', !$baseDir ? basename($filepath) : substr($filepath, strlen($baseDir) + 1));
}
function generatePackageXml($packageINI)
{
$XML = <<<XML
<?xml version="1.0"?>
<package packagerversion="1.4.10" version="2.0"
xmlns="http://pear.php.net/dtd/package-2.0"
xmlns:tasks="http://pear.php.net/dtd/tasks-1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0
http://pear.php.net/dtd/tasks-1.0.xsd
http://pear.php.net/dtd/package-2.0
http://pear.php.net/dtd/package-2.0.xsd" />
XML;
$cfg = parse_ini_file($packageINI, true);
$pkg = new SimpleXMLElement($XML);
$pkg->name = $cfg['package']['name'];
$pkg->channel = $cfg['package']['channel'];
$pkg->summary = $cfg['package']['desc'];
$pkg->description = $cfg['package']['desc'];
$author = parseAuthor($cfg['package']['author']);
$pkg->addChild('lead');
$pkg->lead->name = $author['name'];
$pkg->lead->user = $author['user'];
$pkg->lead->email = $author['email'];
$pkg->lead->active = 'yes';
$datetime = new DateTime('now');
$pkg->date = $datetime->format('Y-m-d');
$pkg->time = $datetime->format('H:i:s');
$pkg->addChild('version');
$pkg->version->release = $cfg['package']['version'];
$pkg->version->api = $cfg['package']['version'];
$pkg->addChild('stability');
$pkg->stability->release = $cfg['package']['stability'];
$pkg->stability->api = $cfg['package']['stability'];
$pkg->license = $cfg['package']['license'];
$pkg->notes = '-';
$pkg->addChild('contents')->addChild('dir')->addAttribute('name', '/');
$pkg->addChild('dependencies')->addChild('required');
foreach ($cfg['require'] as $required => $version) {
$version = parseVersion($version);
$pkg->dependencies->required->addChild($required);
if (isset($version['min'])) {
$pkg->dependencies->required->$required->min = $version['min'];
}
if (isset($version['max'])) {
$pkg->dependencies->required->$required->min = $version['max'];
}
}
$pkg->addChild('phprelease')->addChild('filelist');
$pathToRole = array(
'doc' => 'doc', 'docs' => 'doc', 'examples' => 'doc',
'lib' => 'php', 'src' => 'php',
'test' => 'test', 'tests' => 'test',
);
foreach (array_merge($pathToRole, $cfg['roles'] ?: array()) as $path => $role) {
addRolePath($pkg, $path, $role);
}
return $pkg;
}
function rewritePackageInstallAs($pkg)
{
foreach ($pkg->phprelease->filelist->install as $file) {
if (preg_match('/^src\//', $file['name'])) {
$file['as'] = "Predis/{$file['as']}";
}
}
}
function savePackageXml($xml)
{
$dom = new DOMDocument("1.0");
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($xml->asXML());
file_put_contents('package.xml', $dom->saveXML());
}
function buildPackage()
{
passthru('pear -q package && rm package.xml');
}
function modifyPhpunitXml($file)
{
$cfg = new SimpleXMLElement($file, null, true);
$cfg[0]['bootstrap'] = str_replace('tests/', '', $cfg[0]['bootstrap']);
$cfg->testsuites->testsuite->directory = str_replace('tests/', '', $cfg->testsuites->testsuite->directory);
$cfg->saveXml($file);
}
// -------------------------------------------------------------------------- //
executeWithBackup(__DIR__.'/../phpunit.xml.dist', function ($file) {
modifyPhpunitXml($file);
$pkg = generatePackageXml('package.ini');
rewritePackageInstallAs($pkg);
savePackageXml($pkg);
buildPackage();
});
+3 -3
View File
@@ -19,7 +19,7 @@
$options = array(
'name' => 'predis',
'project_path' => __DIR__ . '/../src',
'project_path' => __DIR__ . '/../lib/',
'compression' => Phar::NONE,
'append_version' => true,
);
@@ -50,9 +50,9 @@ function getPharStub($options)
return <<<EOSTUB
<?php
Phar::mapPhar('predis.phar');
spl_autoload_register(function (\$class) {
spl_autoload_register(function(\$class) {
if (strpos(\$class, 'Predis\\\\') === 0) {
\$file = 'phar://predis.phar/'.strtr(substr(\$class, 7), '\\\', '/').'.php';
\$file = 'phar://predis.phar/'.strtr(\$class, '\\\', '/').'.php';
if (file_exists(\$file)) {
require \$file;
return true;
@@ -19,7 +19,7 @@
// files, but namespaces and classes definitions must follow a precise order
// when dealing with subclassing and inheritance.
//
// The current implementation is pretty naïve, but it should do for now.
// The current implementation is pretty naïve, but it should do for now.
// -------------------------------------------------------------------------- //
class CommandLine
@@ -27,16 +27,16 @@ class CommandLine
public static function getOptions()
{
$parameters = array(
's:' => 'source:',
'o:' => 'output:',
'e:' => 'exclude:',
'E:' => 'exclude-classes:',
's:' => 'source:',
'o:' => 'output:',
'e:' => 'exclude:',
'E:' => 'exclude-classes:',
);
$getops = getopt(implode(array_keys($parameters)), $parameters);
$options = array(
'source' => __DIR__ . "/../src",
'source' => __DIR__ . "/../lib/",
'output' => PredisFile::NS_ROOT . '.php',
'exclude' => array(),
);
@@ -80,10 +80,11 @@ class PredisFile
$this->namespaces = array();
}
public static function from($libraryPath, array $exclude = array())
public static function from($libraryPath, Array $exclude = array())
{
$nsroot = self::NS_ROOT;
$predisFile = new PredisFile();
$libIterator = new RecursiveDirectoryIterator($libraryPath);
$libIterator = new RecursiveDirectoryIterator("$libraryPath$nsroot");
foreach (new RecursiveIteratorIterator($libIterator) as $classFile)
{
@@ -91,7 +92,7 @@ class PredisFile
continue;
}
$namespace = self::NS_ROOT.strtr(str_replace($libraryPath, '', $classFile->getPath()), '/', '\\');
$namespace = strtr(str_replace($libraryPath, '', $classFile->getPath()), '/', '\\');
if (in_array(sprintf('%s\\%s', $namespace, $classFile->getBasename('.php')), $exclude)) {
continue;
@@ -183,7 +184,7 @@ class PredisFile
{
$namespaces = array_fill_keys(array_unique(
array_map(
function ($fqn) { return PhpNamespace::extractName($fqn); },
function($fqn) { return PhpNamespace::extractName($fqn); },
array_keys($dependencyScores)
)
), 0);
@@ -199,7 +200,7 @@ class PredisFile
private function getOrderedClasses(PhpNamespace $phpNamespace, $classes)
{
$nsClassesFQNs = array_map(function ($cl) { return $cl->getFQN(); }, $phpNamespace->getClasses());
$nsClassesFQNs = array_map(function($cl) { return $cl->getFQN(); }, $phpNamespace->getClasses());
$nsOrderedClasses = array();
foreach ($nsClassesFQNs as $nsClassFQN) {
@@ -320,15 +321,13 @@ class PhpUseDirectives implements Countable, IteratorAggregate
{
private $use;
private $aliases;
private $reverseAliases;
private $namespace;
public function __construct(PhpNamespace $namespace)
{
$this->namespace = $namespace;
$this->use = array();
$this->aliases = array();
$this->reverseAliases = array();
$this->namespace = $namespace;
}
public function add($use, $as = null)
@@ -337,35 +336,8 @@ class PhpUseDirectives implements Countable, IteratorAggregate
return;
}
$rename = null;
$this->use[] = $use;
$aliasedClassName = $as ?: PhpClass::extractName($use);
if (isset($this->aliases[$aliasedClassName])) {
$parentNs = $this->getParentNamespace();
if ($parentNs && false !== $pos = strrpos($parentNs, '\\')) {
$parentNs = substr($parentNs, $pos);
}
$newAlias = "{$parentNs}_{$aliasedClassName}";
$rename = (object) array(
'namespace' => $this->namespace,
'from' => $aliasedClassName,
'to' => $newAlias,
);
$this->aliases[$newAlias] = $use;
$as = $newAlias;
} else {
$this->aliases[$aliasedClassName] = $use;
}
if ($as !== null) {
$this->reverseAliases[$use] = $as;
}
return $rename;
$this->aliases[$as ?: PhpClass::extractName($use)] = $use;
}
public function getList()
@@ -380,15 +352,7 @@ class PhpUseDirectives implements Countable, IteratorAggregate
public function getPhpCode()
{
$reverseAliases = $this->reverseAliases;
$reducer = function ($str, $use) use ($reverseAliases) {
if (isset($reverseAliases[$use])) {
return $str .= "use $use as {$reverseAliases[$use]};\n";
} else {
return $str .= "use $use;\n";
}
};
$reducer = function($str, $use) { return $str .= "use $use;\n"; };
return array_reduce($this->getList(), $reducer, '');
}
@@ -398,15 +362,6 @@ class PhpUseDirectives implements Countable, IteratorAggregate
return $this->namespace;
}
public function getParentNamespace()
{
if (false !== $pos = strrpos($this->namespace, '\\')) {
return substr($this->namespace, 0, $pos);
}
return '';
}
public function getFQN($className)
{
if (($nsSepFirst = strpos($className, '\\')) === false) {
@@ -473,19 +428,10 @@ LICENSE;
private function extractData()
{
$renames = array();
$useDirectives = $this->getNamespace()->getUseDirectives();
$useExtractor = function ($m) use ($useDirectives, &$renames) {
array_shift($m);
if (isset($m[1])) {
$m[1] = str_replace(" as ", '', $m[1]);
}
if ($rename = call_user_func_array(array($useDirectives, 'add'), $m)) {
$renames[] = $rename;
}
$useExtractor = function($m) use($useDirectives) {
$useDirectives->add(($namespacedPath = $m[1]));
};
$classBuffer = stream_get_contents(fopen($this->getFile()->getPathname(), 'r'));
@@ -497,10 +443,6 @@ LICENSE;
$classBuffer = preg_replace('/namespace\s+[\w\d_\\\\]+;\s?/', '', $classBuffer);
$classBuffer = preg_replace_callback('/use\s+([\w\d_\\\\]+)(\s+as\s+.*)?;\s?\n?/', $useExtractor, $classBuffer);
foreach ($renames as $rename) {
$classBuffer = str_replace($rename->from, $rename->to, $classBuffer);
}
$this->body = trim($classBuffer);
$this->extractHierarchy();
@@ -511,7 +453,7 @@ LICENSE;
$implements = array();
$extends = array();
$extractor = function ($iterator, $callback) {
$extractor = function($iterator, $callback) {
$className = '';
$iterator->seek($iterator->key() + 1);
@@ -522,7 +464,8 @@ LICENSE;
if (preg_match('/\s?,\s?/', $token)) {
$callback(trim($className));
$className = '';
} else if ($token == '{') {
}
else if ($token == '{') {
$callback(trim($className));
return;
}
@@ -567,13 +510,13 @@ LICENSE;
break;
case T_IMPLEMENTS:
$extractor($iterator, function ($fqn) use (&$implements) {
$extractor($iterator, function($fqn) use (&$implements) {
$implements[] = $fqn;
});
break;
case T_EXTENDS:
$extractor($iterator, function ($fqn) use (&$extends) {
$extractor($iterator, function($fqn) use (&$extends) {
$extends[] = $fqn;
});
break;
@@ -13,11 +13,11 @@
// -------------------------------------------------------------------------- //
// This script can be used to automatically generate a file with the scheleton
// of a test case to test a Redis command by specifying the name of the class
// in the Predis\Command namespace (only classes in this namespace are valid).
// in the Predis\Commands namespace (only classes in this namespace are valid).
// For example, to generate a test case for SET (which is represented by the
// Predis\Command\StringSet class):
// Predis\Commands\StringSet class):
//
// $ ./bin/generate-command-test --class=StringSet
// $ ./bin/generate-command-test.php --class=StringSet
//
// Here is a list of optional arguments:
//
@@ -33,14 +33,14 @@
// is explicitly specified.
// -------------------------------------------------------------------------- //
use Predis\Command\CommandInterface;
use Predis\Command\PrefixableCommandInterface;
use Predis\Commands\ICommand;
use Predis\Commands\IPrefixable;
class CommandTestCaseGenerator
{
private $options;
public function __construct(array $options)
public function __construct(Array $options)
{
if (!isset($options['class'])) {
throw new RuntimeException("Missing 'class' option.");
@@ -61,7 +61,7 @@ class CommandTestCaseGenerator
$options = array(
'overwrite' => false,
'tests' => __DIR__.'/../tests/Predis',
'tests' => __DIR__.'/../tests',
);
foreach ($getops as $option => $value) {
@@ -92,10 +92,10 @@ class CommandTestCaseGenerator
throw new RuntimeException("Missing 'class' option.");
}
$options['fqn'] = "Predis\\Command\\{$options['class']}";
$options['path'] = "Command/{$options['class']}.php";
$options['fqn'] = "Predis\\Commands\\{$options['class']}";
$options['path'] = "Predis/Commands/{$options['class']}.php";
$source = __DIR__.'/../src/'.$options['path'];
$source = __DIR__.'/../lib/'.$options['path'];
if (!file_exists($source)) {
throw new RuntimeException("Cannot find class file for {$options['fqn']} in $source.");
}
@@ -116,8 +116,7 @@ class CommandTestCaseGenerator
return $this->options['realm'];
}
$fqnParts = explode('\\', $this->options['fqn']);
$class = array_pop($fqnParts);
$class = array_pop(explode('\\', $this->options['fqn']));
list($realm,) = preg_split('/([[:upper:]][[:lower:]]+)/', $class, 2, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
return strtolower($realm);
@@ -130,15 +129,11 @@ class CommandTestCaseGenerator
if (!$reflection->isInstantiable()) {
throw new RuntimeException("Class $class must be instantiable, abstract classes or interfaces are not allowed.");
}
if (!$reflection->implementsInterface('Predis\Command\CommandInterface')) {
throw new RuntimeException("Class $class must implement Predis\Command\CommandInterface.");
if (!$reflection->implementsInterface('Predis\Commands\ICommand')) {
throw new RuntimeException("Class $class must implement the Predis\Commands\ICommand interface.");
}
/*
* @var CommandInterface
*/
$instance = $reflection->newInstance();
$buffer = $this->getTestCaseBuffer($instance);
return $buffer;
@@ -153,12 +148,11 @@ class CommandTestCaseGenerator
file_put_contents($options['output'], $this->generate());
}
protected function getTestCaseBuffer(CommandInterface $instance)
protected function getTestCaseBuffer(ICommand $instance)
{
$id = $instance->getId();
$fqn = get_class($instance);
$fqnParts = explode('\\', $fqn);
$class = array_pop($fqnParts) . "Test";
$class = array_pop(explode('\\', $fqn)) . "Test";
$realm = $this->getTestRealm();
$buffer =<<<PHP
@@ -173,13 +167,15 @@ class CommandTestCaseGenerator
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
use \PHPUnit_Framework_TestCase as StandardTestCase;
/**
* @group commands
* @group realm-$realm
*/
class $class extends PredisCommandTestCase
class $class extends CommandTestCase
{
/**
* {@inheritdoc}
@@ -230,7 +226,7 @@ class $class extends PredisCommandTestCase
PHP;
if ($instance instanceof PrefixableCommandInterface) {
if ($instance instanceof IPrefixable) {
$buffer .=<<<PHP
/**
@@ -249,17 +245,6 @@ PHP;
\$this->assertSame(\$expected, \$command->getArguments());
}
/**
* @group disconnected
*/
public function testPrefixKeysIgnoredOnEmptyArguments()
{
\$command = \$this->getCommand();
\$command->prefixKeys('prefix:');
\$this->assertSame(array(), \$command->getArguments());
}
PHP;
}
+2 -12
View File
@@ -5,9 +5,6 @@
"keywords": ["nosql", "redis", "predis"],
"homepage": "http://github.com/nrk/predis",
"license": "MIT",
"support": {
"issues": "https://github.com/nrk/predis/issues"
},
"authors": [
{
"name": "Daniele Alessandri",
@@ -16,16 +13,9 @@
}
],
"require": {
"php": ">=5.3.2"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"suggest": {
"ext-phpiredis": "Allows faster serialization and deserialization of the Redis protocol",
"ext-curl": "Allows access to Webdis when paired with phpiredis"
"php": ">=5.3.0"
},
"autoload": {
"psr-4": {"Predis\\": "src/"}
"psr-0": {"Predis": "lib/"}
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require 'SharedConfigurations.php';
// Developers can customize the distribution strategy used by the client
// to distribute keys among a cluster of servers simply by creating a class
// that implements the Predis\Distribution\IDistributionStrategy interface.
use Predis\Distribution\IDistributionStrategy;
use Predis\Network\PredisCluster;
class NaiveDistributionStrategy implements IDistributionStrategy
{
private $nodes;
private $nodesCount;
public function __constructor()
{
$this->nodes = array();
$this->nodesCount = 0;
}
public function add($node, $weight = null)
{
$this->nodes[] = $node;
$this->nodesCount++;
}
public function remove($node)
{
$this->nodes = array_filter($this->nodes, function($n) use($node) {
return $n !== $node;
});
$this->nodesCount = count($this->nodes);
}
public function get($key)
{
$count = $this->nodesCount;
if ($count === 0) {
throw new RuntimeException('No connections');
}
return $this->nodes[$count > 1 ? abs(crc32($key) % $count) : 0];
}
public function generateKey($value)
{
return crc32($value);
}
}
$options = array(
'cluster' => function() {
$distributor = new NaiveDistributionStrategy();
return new PredisCluster($distributor);
},
);
$client = new Predis\Client($multiple_servers, $options);
for ($i = 0; $i < 100; $i++) {
$client->set("key:$i", str_pad($i, 4, '0', 0));
$client->get("key:$i");
}
$server1 = $client->getClientFor('first')->info();
$server2 = $client->getClientFor('second')->info();
printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
);
@@ -9,29 +9,28 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// This is a basic example on how to use the Predis\DispatcherLoop class.
//
// To see this example in action you can just use redis-cli and publish some
// messages to the 'events' and 'control' channel, e.g.:
/*
This is a basic example on how to use the Predis\DispatcherLoop class.
// ./redis-cli
// PUBLISH events first
// PUBLISH events second
// PUBLISH events third
// PUBLISH control terminate_dispatcher
To see this example in action you can just use redis-cli and publish some
messages to the 'events' and 'control' channel, e.g.:
./redis-cli
PUBLISH events first
PUBLISH events second
PUBLISH events third
PUBLISH control terminate_dispatcher
*/
// Create a client and disable r/w timeout on the socket
$client = new Predis\Client($single_server + array('read_write_timeout' => 0));
// Return an initialized PubSub consumer instance from the client.
$pubsub = $client->pubSubLoop();
// Create a Predis\DispatcherLoop instance and attach a bunch of callbacks.
$dispatcher = new Predis\PubSub\DispatcherLoop($client);
// Create a dispatcher loop instance and attach a bunch of callbacks.
$dispatcher = new Predis\PubSub\DispatcherLoop($pubsub);
// Demonstrate how to use a callable class as a callback for the dispatcher loop.
// Demonstrate how to use a callable class as a callback for Predis\DispatcherLoop.
class EventsListener implements Countable
{
private $events;
@@ -61,7 +60,7 @@ class EventsListener implements Countable
$dispatcher->attachCallback('events', ($events = new EventsListener()));
// Attach a function to control the dispatcher loop termination with a message.
$dispatcher->attachCallback('control', function ($payload) use ($dispatcher) {
$dispatcher->attachCallback('control', function($payload) use ($dispatcher) {
if ($payload === 'terminate_dispatcher') {
$dispatcher->stop();
}
@@ -72,8 +71,8 @@ $dispatcher->attachCallback('control', function ($payload) use ($dispatcher) {
$dispatcher->run();
// Display our achievements!
echo "We received {$events->count()} messages!", PHP_EOL;
echo "We received {$events->count()} messages!\n";
// Say goodbye :-)
$version = redis_version($client->info());
echo "Goodbye from Redis $version!", PHP_EOL;
$info = $client->info();
print_r("Goodbye from Redis v{$info['redis_version']}!\n");
+37
View File
@@ -0,0 +1,37 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require 'SharedConfigurations.php';
// Predis ships with a KeyPrefixProcessor class that is used to transparently
// prefix each key before sending commands to Redis, even for complex commands
// such as SORT, ZUNIONSTORE and ZINTERSTORE. Key prefixes are useful to create
// user-level namespaces for you keyspace, thus eliminating the need for separate
// logical databases.
$client = new Predis\Client($single_server, array('prefix' => 'nrk:'));
$client->mset(array('foo' => 'bar', 'lol' => 'wut'));
var_dump($client->mget('foo', 'lol'));
/*
array(2) {
[0]=> string(3) "bar"
[1]=> string(3) "wut"
}
*/
var_dump($client->keys('*'));
/*
array(2) {
[0]=> string(7) "nrk:foo"
[1]=> string(7) "nrk:lol"
}
*/
@@ -9,16 +9,16 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// Predis supports master / slave replication scenarios where write operations
// are performed on the master server and read operations are executed against
// one of the slaves. The behavior of commands or EVAL scripts can be customized
// at will. As soon as a write operation is performed the client switches to the
// master server for all the subsequent requests (either reads and writes).
// Predis supports master / slave replication scenarios where write operations are
// performed on the master server and read operations are executed against one of
// the slaves. The behaviour of commands or EVAL scripts can be customized at will.
// As soon as a write operation is performed, all the subsequent requests (reads
// or writes) will be served by the master server.
//
// This example must be executed using the second Redis server configured as the
// slave of the first one (see the "SLAVEOF" command).
// This example must be executed with the second Redis server acting as the slave
// of the first one using the SLAVEOF command.
//
$parameters = array(
@@ -33,20 +33,20 @@ $client = new Predis\Client($parameters, $options);
// Read operation.
$exists = $client->exists('foo') ? 'yes' : 'no';
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Does 'foo' exist on {$current->alias}? $exists.", PHP_EOL;
echo "Does 'foo' exist on {$current->alias}? $exists.\n";
// Write operation.
$client->set('foo', 'bar');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "Now 'foo' has been set to 'bar' on {$current->alias}!", PHP_EOL;
echo "Now 'foo' has been set to 'bar' on {$current->alias}!\n";
// Read operation.
$bar = $client->get('foo');
$current = $client->getConnection()->getCurrent()->getParameters();
echo "We fetched 'foo' from {$current->alias} and its value is '$bar'.", PHP_EOL;
echo "We just fetched 'foo' from {$current->alias} and its value is '$bar'.\n";
/* OUTPUT:
Does 'foo' exist on slave? yes.
Now 'foo' has been set to 'bar' on master!
We fetched 'foo' from master and its value is 'bar'.
We just fetched 'foo' from master and its value is 'bar'.
*/
@@ -9,37 +9,35 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// Predis allows to set Lua scripts as read-only operations for replication.
// This works for both EVAL and EVALSHA and also for the client-side abstraction
// built upon them (Predis\Command\ScriptCommand). This example shows a slightly
// more complex configuration that injects a new script command in the server
// profile used by the new client instance and marks it marks it as a read-only
// operation for replication so that it will be executed on slaves.
// Predis allows to set Lua scripts as read-only operations in the context of
// replication. This works for both EVAL and EVALSHA and also for the client-side
// abstraction built upon them (Predis\Commands\ScriptedCommand). This example
// shows a slightly more complex configuration that injects a new scripted command
// in the server profile used by the new client instance and marks it marks it as
// a read-only operation for replication so that it will be executed on slaves.
use Predis\Command\ScriptCommand;
use Predis\Connection\Aggregate\MasterSlaveReplication;
use Predis\Replication\ReplicationStrategy;
use Predis\Profiles\ServerProfile;
use Predis\Commands\ScriptedCommand;
use Predis\Network\MasterSlaveReplication;
// ------------------------------------------------------------------------- //
// Define a new script command that returns all the fields of a variable number
// of hashes with a single roundtrip.
// Define a new scripted command that returns all the fields
// of a variable number of hashes with a single roundtrip.
class HashMultipleGetAll extends ScriptCommand
{
const BODY = <<<LUA
class HashMultipleGetAll extends ScriptedCommand {
const BODY = <<<EOS
local hashes = {}
for _, key in pairs(KEYS) do
table.insert(hashes, key)
table.insert(hashes, redis.call('hgetall', key))
end
return hashes
LUA;
EOS;
public function getScript()
{
public function getScript() {
return self::BODY;
}
}
@@ -52,17 +50,15 @@ $parameters = array(
);
$options = array(
'profile' => function ($options, $option) {
$profile = $options->getDefault($option);
'profile' => function($options) {
$profile = ServerProfile::get('2.6');
$profile->defineCommand('hmgetall', 'HashMultipleGetAll');
return $profile;
},
'replication' => function () {
$strategy = new ReplicationStrategy();
$strategy->setScriptReadOnly(HashMultipleGetAll::BODY);
$replication = new MasterSlaveReplication($strategy);
'replication' => function($options) {
$replication = new MasterSlaveReplication();
$replication->setScriptReadOnly(HashMultipleGetAll::BODY);
return $replication;
},
@@ -81,5 +77,5 @@ $hashes = $client->hmgetall('metavars', 'servers');
$replication = $client->getConnection();
$stillOnSlave = $replication->getCurrent() === $replication->getConnectionById('slave');
echo 'Is still on slave? ', $stillOnSlave ? 'YES!' : 'NO!', PHP_EOL;
echo "Is still on slave? ", $stillOnSlave ? 'YES' : 'NO', "!\n";
var_export($hashes);
@@ -9,10 +9,10 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// This is a basic example on how to use the Predis\Monitor\Consumer class. You
// can use redis-cli to send commands to the same Redis instance your client is
// This is a basic example on how to use the Predis\MonitorContext class.
// You can use redis-cli to send commands to the same Redis instance your client is
// connected to, and then type "ECHO QUIT_MONITOR" in redis-cli when you want to
// exit the monitor loop and terminate this script in a graceful way.
@@ -25,20 +25,20 @@ $timestamp = new DateTime();
foreach (($monitor = $client->monitor()) as $event) {
$timestamp->setTimestamp((int) $event->timestamp);
// If we notice a ECHO command with the message QUIT_MONITOR, we stop the
// monitor consumer and then break the loop.
// If we notice a ECHO command with the message QUIT_MONITOR, we close the
// monitor context and then break the loop.
if ($event->command === 'ECHO' && $event->arguments === '"QUIT_MONITOR"') {
echo 'Exiting the monitor loop...', PHP_EOL;
$monitor->stop();
echo "Exiting the monitor loop...\n";
$monitor->closeContext();
break;
}
echo "* Received {$event->command} on DB {$event->database} at {$timestamp->format(DateTime::W3C)}", PHP_EOL;
echo "* Received {$event->command} on DB {$event->database} at {$timestamp->format(DateTime::W3C)}\n";
if (isset($event->arguments)) {
echo " Arguments: {$event->arguments}", PHP_EOL;
echo " Arguments: {$event->arguments}\n";
}
}
// Say goodbye :-)
$version = redis_version($client->info());
echo "Goodbye from Redis $version!", PHP_EOL;
$info = $client->info();
print_r("Goodbye from Redis v{$info['redis_version']}!\n");
@@ -9,7 +9,7 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// This is an implementation of an atomic client-side ZPOP using the support for
// check-and-set (CAS) operations with MULTI/EXEC transactions, as described in
@@ -19,10 +19,9 @@ require __DIR__.'/shared.php';
//
// ./redis-cli
// SELECT 15
// ZADD zset 1 a 2 b 3 c
//
// Then execute this script four times and see its output.
//
// ZADD zset 1 a
// ZADD zset 2 b
// ZADD zset 3 c
function zpop($client, $key)
{
@@ -34,7 +33,7 @@ function zpop($client, $key)
// which the client bails out with an exception.
);
$client->transaction($options, function ($tx) use ($key, &$element) {
$client->multiExec($options, function($tx) use ($key, &$element) {
@list($element) = $tx->zrange($key, 0, 0);
if (isset($element)) {
@@ -49,4 +48,4 @@ function zpop($client, $key)
$client = new Predis\Client($single_server);
$zpopped = zpop($client, 'zset');
echo isset($zpopped) ? "ZPOPed $zpopped" : 'Nothing to ZPOP!', PHP_EOL;
echo isset($zpopped) ? "ZPOPed $zpopped" : "Nothing to ZPOP!", "\n";
+38
View File
@@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require 'SharedConfigurations.php';
// redis can set keys and their relative values in one go
// using MSET, then the same values can be retrieved with
// a single command using MGET.
$mkv = array(
'usr:0001' => 'First user',
'usr:0002' => 'Second user',
'usr:0003' => 'Third user'
);
$client = new Predis\Client($single_server);
$client->mset($mkv);
$retval = $client->mget(array_keys($mkv));
print_r($retval);
/* OUTPUT:
Array
(
[0] => First user
[1] => Second user
[2] => Third user
)
*/
@@ -9,15 +9,15 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// When you have a whole set of consecutive commands to send to a redis server,
// you can use a pipeline to dramatically improve performances. Pipelines can
// greatly reduce the effects of network round-trips.
// When you have a whole set of consecutive commands to send to
// a redis server, you can use a pipeline to improve performances.
$client = new Predis\Client($single_server);
$responses = $client->pipeline(function ($pipe) {
$replies = $client->pipeline(function($pipe) {
$pipe->ping();
$pipe->flushdb();
$pipe->incrby('counter', 10);
$pipe->incrby('counter', 30);
@@ -26,20 +26,22 @@ $responses = $client->pipeline(function ($pipe) {
$pipe->mget('does_not_exist', 'counter');
});
var_export($responses);
print_r($replies);
/* OUTPUT:
array (
0 => Predis\Response\Status::__set_state(array(
'payload' => 'OK',
)),
1 => 10,
2 => 40,
3 => true,
4 => '40',
5 => array (
0 => NULL,
1 => '40',
),
Array
(
[0] => 1
[1] => 1
[2] => 10
[3] => 40
[4] => 1
[5] => 40
[6] => Array
(
[0] =>
[1] => 40
)
)
*/
@@ -9,16 +9,16 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// Starting from Redis 2.0 clients can subscribe and listen for events published
// on certain channels using a Publish/Subscribe (PUB/SUB) approach.
// Redis 2.0 features new commands that allow clients to subscribe for
// events published on certain channels (PUBSUB).
// Create a client and disable r/w timeout on the socket
$client = new Predis\Client($single_server + array('read_write_timeout' => 0));
// Initialize a new pubsub consumer.
$pubsub = $client->pubSubLoop();
// Initialize a new pubsub context
$pubsub = $client->pubSub();
// Subscribe to your channels
$pubsub->subscribe('control_channel', 'notifications');
@@ -30,30 +30,32 @@ $pubsub->subscribe('control_channel', 'notifications');
foreach ($pubsub as $message) {
switch ($message->kind) {
case 'subscribe':
echo "Subscribed to {$message->channel}", PHP_EOL;
echo "Subscribed to {$message->channel}\n";
break;
case 'message':
if ($message->channel == 'control_channel') {
if ($message->payload == 'quit_loop') {
echo 'Aborting pubsub loop...', PHP_EOL;
echo "Aborting pubsub loop...\n";
$pubsub->unsubscribe();
} else {
echo "Received an unrecognized command: {$message->payload}.", PHP_EOL;
}
} else {
echo "Received the following message from {$message->channel}:",
PHP_EOL, " {$message->payload}", PHP_EOL, PHP_EOL;
else {
echo "Received an unrecognized command: {$message->payload}.\n";
}
}
else {
echo "Received the following message from {$message->channel}:\n",
" {$message->payload}\n\n";
}
break;
}
}
// Always unset the pubsub consumer instance when you are done! The
// Always unset the pubsub context instance when you are done! The
// class destructor will take care of cleanups and prevent protocol
// desynchronizations between the client and the server.
unset($pubsub);
// Say goodbye :-)
$version = redis_version($client->info());
echo "Goodbye from Redis $version!", PHP_EOL;
$info = $client->info();
print_r("Goodbye from Redis v{$info['redis_version']}!\n");
+49
View File
@@ -0,0 +1,49 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require 'SharedConfigurations.php';
// This example will not work with versions of Redis < 2.6.
//
// Additionally to the EVAL command defined in the current development profile, the new
// Predis\Commands\ScriptedCommand base class can be used to build an higher abstraction
// for our "scripted" commands so that they will appear just like any other command on
// the client-side. This is a quick example used to implement INCREX.
use Predis\Commands\ScriptedCommand;
class IncrementExistingKey extends ScriptedCommand
{
public function getKeysCount()
{
return 1;
}
public function getScript()
{
return
<<<LUA
local cmd = redis.call
if cmd('exists', KEYS[1]) == 1 then
return cmd('incr', KEYS[1])
end
LUA;
}
}
$client = new Predis\Client($single_server, '2.6');
$client->getProfile()->defineCommand('increx', 'IncrementExistingKey');
$client->set('foo', 10);
var_dump($client->increx('foo')); // int(11)
var_dump($client->increx('bar')); // NULL
@@ -11,21 +11,10 @@
require __DIR__.'/../autoload.php';
function redis_version($info)
{
if (isset($info['Server']['redis_version'])) {
return $info['Server']['redis_version'];
} elseif (isset($info['redis_version'])) {
return $info['redis_version'];
} else {
return 'unknown version';
}
}
$single_server = array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 15,
'database' => 15
);
$multiple_servers = array(
@@ -9,15 +9,11 @@
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require 'SharedConfigurations.php';
// This is an example of how you can easily extend an existing connection class
// and trace the execution of commands for debugging purposes. This can be quite
// useful as a starting poing to understand how your application interacts with
// Redis.
use Predis\Command\CommandInterface;
use Predis\Connection\StreamConnection;
use Predis\ConnectionParameters;
use Predis\Commands\ICommand;
use Predis\Network\StreamConnection;
class SimpleDebuggableConnection extends StreamConnection
{
@@ -31,9 +27,9 @@ class SimpleDebuggableConnection extends StreamConnection
parent::connect();
}
private function storeDebug(CommandInterface $command, $direction)
private function storeDebug(ICommand $command, $direction)
{
$firtsArg = $command->getArgument(0);
$firtsArg = $command->getArgument(0);
$timestamp = round(microtime(true) - $this->tstart, 4);
$debug = $command->getId();
@@ -44,19 +40,19 @@ class SimpleDebuggableConnection extends StreamConnection
$this->debugBuffer[] = $debug;
}
public function writeRequest(CommandInterface $command)
public function writeCommand(ICommand $command)
{
parent::writeRequest($command);
parent::writeCommand($command);
$this->storeDebug($command, '->');
}
public function readResponse(CommandInterface $command)
public function readResponse(ICommand $command)
{
$response = parent::readResponse($command);
$reply = parent::readResponse($command);
$this->storeDebug($command, '<-');
return $response;
return $reply;
}
public function getDebugBuffer()
@@ -76,17 +72,18 @@ $client->set('foo', 'bar');
$client->get('foo');
$client->info();
var_export($client->getConnection()->getDebugBuffer());
print_r($client->getConnection()->getDebugBuffer());
/* OUTPUT:
array (
0 => 'SELECT 15 -> 127.0.0.1:6379 [0.0008s]',
1 => 'SELECT 15 <- 127.0.0.1:6379 [0.001s]',
2 => 'SET foo -> 127.0.0.1:6379 [0.001s]',
3 => 'SET foo <- 127.0.0.1:6379 [0.0011s]',
4 => 'GET foo -> 127.0.0.1:6379 [0.0013s]',
5 => 'GET foo <- 127.0.0.1:6379 [0.0015s]',
6 => 'INFO -> 127.0.0.1:6379 [0.0019s]',
7 => 'INFO <- 127.0.0.1:6379 [0.0022s]',
Array
(
[0] => SELECT 15 -> 127.0.0.1:6379 [0.0008s]
[1] => SELECT 15 <- 127.0.0.1:6379 [0.0012s]
[2] => SET foo -> 127.0.0.1:6379 [0.0014s]
[3] => SET foo <- 127.0.0.1:6379 [0.0014s]
[4] => GET foo -> 127.0.0.1:6379 [0.0016s]
[5] => GET foo <- 127.0.0.1:6379 [0.0018s]
[6] => INFO -> 127.0.0.1:6379 [0.002s]
[7] => INFO <- 127.0.0.1:6379 [0.0025s]
)
*/
@@ -9,15 +9,17 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
require 'SharedConfigurations.php';
class ZSetReverseRangeByLex extends ZSetRangeByLex
{
/**
* {@inheritdoc}
*/
public function getId()
{
return 'ZREVRANGEBYLEX';
}
}
// simple set and get scenario
$client = new Predis\Client($single_server);
$client->set('library', 'predis');
$retval = $client->get('library');
var_dump($retval);
/* OUTPUT
string(6) "predis"
*/
-117
View File
@@ -1,117 +0,0 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
// Developers can implement Predis\Distribution\DistributorInterface to create
// their own distributors used by the client to distribute keys among a cluster
// of servers.
use Predis\Cluster\Distributor\DistributorInterface;
use Predis\Cluster\Hash\HashGeneratorInterface;
use Predis\Cluster\PredisStrategy;
use Predis\Connection\Aggregate\PredisCluster;
class NaiveDistributor implements DistributorInterface, HashGeneratorInterface
{
private $nodes;
private $nodesCount;
public function __construct()
{
$this->nodes = array();
$this->nodesCount = 0;
}
public function add($node, $weight = null)
{
$this->nodes[] = $node;
++$this->nodesCount;
}
public function remove($node)
{
$this->nodes = array_filter($this->nodes, function ($n) use ($node) {
return $n !== $node;
});
$this->nodesCount = count($this->nodes);
}
public function getSlot($hash)
{
return $this->nodesCount > 1 ? abs($hash % $this->nodesCount) : 0;
}
public function getBySlot($slot)
{
return isset($this->nodes[$slot]) ? $this->nodes[$slot] : null;
}
public function getByHash($hash)
{
if (!$this->nodesCount) {
throw new RuntimeException('No connections.');
}
$slot = $this->getSlot($hash);
$node = $this->getBySlot($slot);
return $node;
}
public function get($value)
{
$hash = $this->hash($value);
$node = $this->getByHash($hash);
return $node;
}
public function hash($value)
{
return crc32($value);
}
public function getHashGenerator()
{
return $this;
}
}
$options = array(
'cluster' => function () {
$distributor = new NaiveDistributor();
$strategy = new PredisStrategy($distributor);
$cluster = new PredisCluster($strategy);
return $cluster;
},
);
$client = new Predis\Client($multiple_servers, $options);
for ($i = 0; $i < 100; ++$i) {
$client->set("key:$i", str_pad($i, 4, '0', 0));
$client->get("key:$i");
}
$server1 = $client->getClientFor('first')->info();
$server2 = $client->getClientFor('second')->info();
if (isset($server1['Keyspace'], $server2['Keyspace'])) {
$server1 = $server1['Keyspace'];
$server2 = $server2['Keyspace'];
}
printf("Server '%s' has %d keys while server '%s' has %d keys.\n",
'first', $server1['db15']['keys'], 'second', $server2['db15']['keys']
);
-57
View File
@@ -1,57 +0,0 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
$client = new Predis\Client($single_server);
// Plain old SET and GET example...
$client->set('library', 'predis');
$response = $client->get('library');
var_export($response); echo PHP_EOL;
/* OUTPUT: 'predis' */
// Redis has the MSET and MGET commands to set or get multiple keys in one go,
// cases like this Predis accepts arguments for variadic commands both as a list
// of arguments or an array containing all of the keys and/or values.
$mkv = array(
'uid:0001' => '1st user',
'uid:0002' => '2nd user',
'uid:0003' => '3rd user',
);
$client->mset($mkv);
$response = $client->mget(array_keys($mkv));
var_export($response); echo PHP_EOL;
/* OUTPUT:
array (
0 => '1st user',
1 => '2nd user',
2 => '3rd user',
) */
// Predis can also send "raw" commands to Redis. The difference between sending
// commands to Redis the usual way and the "raw" way is that in the latter case
// their arguments are not filtered nor responses coming from Redis are parsed.
$response = $client->executeRaw(array(
'MGET', 'uid:0001', 'uid:0002', 'uid:0003',
));
var_export($response); echo PHP_EOL;
/* OUTPUT:
array (
0 => '1st user',
1 => '2nd user',
2 => '3rd user',
) */
-36
View File
@@ -1,36 +0,0 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
// Predis can prefix keys found in commands arguments before sending commands to
// Redis, even for complex commands such as SORT, ZUNIONSTORE and ZINTERSTORE.
// Prefixing keys can be useful to create user-level namespaces for you keyspace
// thus reducing the need for separate logical databases in certain scenarios.
$client = new Predis\Client($single_server, array('prefix' => 'nrk:'));
$client->mset(array('foo' => 'bar', 'lol' => 'wut'));
var_export($client->mget('foo', 'lol'));
/*
array (
0 => 'bar',
1 => 'wut',
)
*/
var_export($client->keys('*'));
/*
array (
0 => 'nrk:foo',
1 => 'nrk:lol',
)
*/
-71
View File
@@ -1,71 +0,0 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
// This example will not work with versions of Redis < 2.6.
//
// Additionally to the EVAL command defined in the current development profile,
// the Predis\Command\ScriptCommand class can be used to build an higher level
// abstraction for "scriptable" commands so that they will appear just like any
// other command on the client-side. This is a quick example used to implement
// INCREX.
use Predis\Command\ScriptCommand;
class IncrementExistingKeysBy extends ScriptCommand
{
public function getKeysCount()
{
// Tell Predis to use all the arguments but the last one as arguments
// for KEYS. The last one will be used to populate ARGV.
return -1;
}
public function getScript()
{
return <<<LUA
local cmd, insert = redis.call, table.insert
local increment, results = ARGV[1], { }
for idx, key in ipairs(KEYS) do
if cmd('exists', key) == 1 then
insert(results, idx, cmd('incrby', key, increment))
else
insert(results, idx, false)
end
end
return results
LUA;
}
}
$client = new Predis\Client($single_server, array(
'profile' => function ($options) {
$profile = $options->getDefault('profile');
$profile->defineCommand('increxby', 'IncrementExistingKeysBy');
return $profile;
},
));
$client->mset('foo', 10, 'foobar', 100);
var_export($client->increxby('foo', 'foofoo', 'foobar', 50));
/*
array (
0 => 60,
1 => NULL,
2 => 150,
)
*/
-99
View File
@@ -1,99 +0,0 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
use Predis\Collection\Iterator;
// Starting from Redis 2.8, clients can iterate incrementally over collections
// without blocking the server like it happens when a command such as KEYS is
// executed on a Redis instance storing millions of keys. These commands are:
//
// - SCAN (iterates over the keyspace)
// - SSCAN (iterates over members of a set)
// - ZSCAN (iterates over members and ranks of a sorted set)
// - HSCAN (iterates over fields and values of an hash).
// Predis provides a specialized abstraction for each command based on standard
// SPL iterators making it possible to easily consume SCAN-based iterations in
// your PHP code.
//
// See http://redis.io/commands/scan for more details.
//
// Create a client using `2.8` as a server profile (needs Redis 2.8!)
$client = new Predis\Client($single_server, array('profile' => '2.8'));
// Prepare some keys for our example
$client->del('predis:set', 'predis:zset', 'predis:hash');
for ($i = 0; $i < 5; ++$i) {
$client->sadd('predis:set', "member:$i");
$client->zadd('predis:zset', -$i, "member:$i");
$client->hset('predis:hash', "field:$i", "value:$i");
}
// === Keyspace iterator based on SCAN ===
echo 'Scan the keyspace matching only our prefixed keys:', PHP_EOL;
foreach (new Iterator\Keyspace($client, 'predis:*') as $key) {
echo " - $key", PHP_EOL;
}
/* OUTPUT
Scan the keyspace matching only our prefixed keys:
- predis:zset
- predis:set
- predis:hash
*/
// === Set iterator based on SSCAN ===
echo 'Scan members of `predis:set`:', PHP_EOL;
foreach (new Iterator\SetKey($client, 'predis:set') as $member) {
echo " - $member", PHP_EOL;
}
/* OUTPUT
Scan members of `predis:set`:
- member:1
- member:4
- member:0
- member:3
- member:2
*/
// === Sorted set iterator based on ZSCAN ===
echo 'Scan members and ranks of `predis:zset`:', PHP_EOL;
foreach (new Iterator\SortedSetKey($client, 'predis:zset') as $member => $rank) {
echo " - $member [rank: $rank]", PHP_EOL;
}
/* OUTPUT
Scan members and ranks of `predis:zset`:
- member:4 [rank: -4]
- member:3 [rank: -3]
- member:2 [rank: -2]
- member:1 [rank: -1]
- member:0 [rank: 0]
*/
// === Hash iterator based on HSCAN ===
echo 'Scan fields and values of `predis:hash`:', PHP_EOL;
foreach (new Iterator\HashKey($client, 'predis:hash') as $field => $value) {
echo " - $field => $value", PHP_EOL;
}
/* OUTPUT
Scan fields and values of `predis:hash`:
- field:0 => value:0
- field:1 => value:1
- field:2 => value:2
- field:3 => value:3
- field:4 => value:4
*/
-52
View File
@@ -1,52 +0,0 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
// This example demonstrates how to use Predis to save PHP sessions on Redis.
//
// The value of `session.gc_maxlifetime` in `php.ini` will be used by default as
// the TTL for keys holding session data but this value can be overridden when
// creating the session handler instance using the `gc_maxlifetime` option.
//
// NOTE: this class requires PHP >= 5.4 but can be used on PHP 5.3 if a polyfill
// for SessionHandlerInterface is provided either by you or an external package
// like `symfony/http-foundation`.
//
// See http://www.php.net/class.sessionhandlerinterface.php for more details.
//
if (!interface_exists('SessionHandlerInterface')) {
die('ATTENTION: the session handler implemented by Predis requires PHP >= 5.4.0 '.
"or a polyfill for SessionHandlerInterface provided by an external package.\n");
}
// Instantiate a new client just like you would normally do. Using a prefix for
// keys will effectively prefix all session keys with the specified string.
$client = new Predis\Client($single_server, array('prefix' => 'sessions:'));
// Set `gc_maxlifetime` to specify a time-to-live of 5 seconds for session keys.
$handler = new Predis\Session\Handler($client, array('gc_maxlifetime' => 5));
// Register the session handler.
$handler->register();
// We just set a fixed session ID only for the sake of our example.
session_id('example_session_id');
session_start();
if (isset($_SESSION['foo'])) {
echo "Session has `foo` set to {$_SESSION['foo']}", PHP_EOL;
} else {
$_SESSION['foo'] = $value = mt_rand();
echo "Empty session, `foo` has been set with $value", PHP_EOL;
}
@@ -12,7 +12,7 @@
namespace Predis;
/**
* Implements a lightweight PSR-0 compliant autoloader for Predis.
* Implements a lightweight PSR-0 compliant autoloader.
*
* @author Eric Naeseth <eric@thumbtack.com>
* @author Daniele Alessandri <suppakilla@gmail.com>
@@ -29,18 +29,18 @@ class Autoloader
public function __construct($baseDirectory = __DIR__)
{
$this->directory = $baseDirectory;
$this->prefix = __NAMESPACE__.'\\';
$this->prefix = __NAMESPACE__ . '\\';
$this->prefixLength = strlen($this->prefix);
}
/**
* Registers the autoloader class with the PHP SPL autoloader.
*
* @param bool $prepend Prepend the autoloader on the stack instead of appending it.
* @param boolean $prepend Prepend the autoloader on the stack instead of appending it.
*/
public static function register($prepend = false)
{
spl_autoload_register(array(new self(), 'autoload'), true, $prepend);
spl_autoload_register(array(new self, 'autoload'), true, $prepend);
}
/**
@@ -52,11 +52,7 @@ class Autoloader
{
if (0 === strpos($className, $this->prefix)) {
$parts = explode('\\', substr($className, $this->prefixLength));
$filepath = $this->directory.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.php';
if (is_file($filepath)) {
require $filepath;
}
require($this->directory.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.php');
}
}
}
+399
View File
@@ -0,0 +1,399 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis;
use Predis\Commands\ICommand;
use Predis\Options\IClientOptions;
use Predis\Network\IConnection;
use Predis\Network\IConnectionSingle;
use Predis\Profiles\IServerProfile;
use Predis\Options\ClientOptions;
use Predis\Profiles\ServerProfile;
use Predis\PubSub\PubSubContext;
use Predis\Pipeline\PipelineContext;
use Predis\Transaction\MultiExecContext;
/**
* Main class that exposes the most high-level interface to interact with Redis.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class Client
{
const VERSION = '0.7.2';
private $options;
private $profile;
private $connection;
private $connections;
/**
* Initializes a new client with optional connection parameters and client options.
*
* @param mixed $parameters Connection parameters for one or multiple servers.
* @param mixed $options Options that specify certain behaviours for the client.
*/
public function __construct($parameters = null, $options = null)
{
$options = $this->filterOptions($options);
$this->options = $options;
$this->profile = $options->profile;
$this->connections = $options->connections;
$this->connection = $this->initializeConnection($parameters);
}
/**
* Creates an instance of Predis\Options\ClientOptions from various types of
* arguments (string, array, Predis\Profiles\ServerProfile) or returns the
* passed object if it is an instance of Predis\Options\ClientOptions.
*
* @param mixed $options Client options.
* @return ClientOptions
*/
protected function filterOptions($options)
{
if ($options === null) {
return new ClientOptions();
}
if (is_array($options)) {
return new ClientOptions($options);
}
if ($options instanceof IClientOptions) {
return $options;
}
if ($options instanceof IServerProfile || is_string($options)) {
return new ClientOptions(array('profile' => $options));
}
throw new \InvalidArgumentException("Invalid type for client options");
}
/**
* Initializes one or multiple connection (cluster) objects from various
* types of arguments (string, array) or returns the passed object if it
* implements the Predis\Network\IConnection interface.
*
* @param mixed $parameters Connection parameters or instance.
* @return IConnection
*/
protected function initializeConnection($parameters)
{
if ($parameters instanceof IConnection) {
return $parameters;
}
if (is_array($parameters) && isset($parameters[0])) {
$replication = isset($this->options->replication) && $this->options->replication;
$connection = $this->options->{$replication ? 'replication' : 'cluster'};
$initializer = $replication ? 'createReplication' : 'createCluster';
return $this->connections->$initializer($connection, $parameters, $this->profile);
}
return $this->connections->create($parameters, $this->profile);
}
/**
* Returns the server profile used by the client.
*
* @return IServerProfile
*/
public function getProfile()
{
return $this->profile;
}
/**
* Returns the client options specified upon initialization.
*
* @return ClientOptions
*/
public function getOptions()
{
return $this->options;
}
/**
* Returns the connection factory object used by the client.
*
* @return IConnectionFactory
*/
public function getConnectionFactory()
{
return $this->connections;
}
/**
* Returns a new instance of a client for the specified connection when the
* client is connected to a cluster. The new instance will use the same
* options of the original client.
*
* @return Client
*/
public function getClientFor($connectionAlias)
{
if (($connection = $this->getConnection($connectionAlias)) === null) {
throw new \InvalidArgumentException("Invalid connection alias: '$connectionAlias'");
}
return new Client($connection, $this->options);
}
/**
* Opens the connection to the server.
*/
public function connect()
{
$this->connection->connect();
}
/**
* Disconnects from the server.
*/
public function disconnect()
{
$this->connection->disconnect();
}
/**
* Disconnects from the server.
*
* This method is an alias of disconnect().
*/
public function quit()
{
$this->disconnect();
}
/**
* Checks if the underlying connection is connected to Redis.
*
* @return Boolean True means that the connection is open.
* False means that the connection is closed.
*/
public function isConnected()
{
return $this->connection->isConnected();
}
/**
* Returns the underlying connection instance or, when connected to a cluster,
* one of the connection instances identified by its alias.
*
* @param string $id The alias of a connection when connected to a cluster.
* @return IConnection
*/
public function getConnection($id = null)
{
if (isset($id)) {
if (!Helpers::isAggregated($this->connection)) {
$message = 'Retrieving connections by alias is supported only with aggregated connections (cluster or replication)';
throw new NotSupportedException($message);
}
return $this->connection->getConnectionById($id);
}
return $this->connection;
}
/**
* Dinamically invokes a Redis command with the specified arguments.
*
* @param string $method The name of a Redis command.
* @param array $arguments The arguments for the command.
* @return mixed
*/
public function __call($method, $arguments)
{
$command = $this->profile->createCommand($method, $arguments);
return $this->connection->executeCommand($command);
}
/**
* Creates a new instance of the specified Redis command.
*
* @param string $method The name of a Redis command.
* @param array $arguments The arguments for the command.
* @return ICommand
*/
public function createCommand($method, $arguments = array())
{
return $this->profile->createCommand($method, $arguments);
}
/**
* Executes the specified Redis command.
*
* @param ICommand $command A Redis command.
* @return mixed
*/
public function executeCommand(ICommand $command)
{
return $this->connection->executeCommand($command);
}
/**
* Executes the specified Redis command on all the nodes of a cluster.
*
* @param ICommand $command A Redis command.
* @return array
*/
public function executeCommandOnShards(ICommand $command)
{
if (Helpers::isCluster($this->connection)) {
$replies = array();
foreach ($this->connection as $connection) {
$replies[] = $connection->executeCommand($command);
}
return $replies;
}
return array($this->connection->executeCommand($command));
}
/**
* Calls the specified initializer method on $this with 0, 1 or 2 arguments.
*
* TODO: Invert $argv and $initializer.
*
* @param array $argv Arguments for the initializer.
* @param string $initializer The initializer method.
* @return mixed
*/
private function sharedInitializer($argv, $initializer)
{
switch (count($argv)) {
case 0:
return $this->$initializer();
case 1:
list($arg0) = $argv;
return is_array($arg0) ? $this->$initializer($arg0) : $this->$initializer(null, $arg0);
case 2:
list($arg0, $arg1) = $argv;
return $this->$initializer($arg0, $arg1);
default:
return $this->$initializer($this, $argv);
}
}
/**
* Creates a new pipeline context and returns it, or returns the results of
* a pipeline executed inside the optionally provided callable object.
*
* @param mixed $arg,... Options for the context, a callable object, or both.
* @return PipelineContext|array
*/
public function pipeline(/* arguments */)
{
return $this->sharedInitializer(func_get_args(), 'initPipeline');
}
/**
* Pipeline context initializer.
*
* @param array $options Options for the context.
* @param mixed $callable Optional callable object used to execute the context.
* @return PipelineContext|array
*/
protected function initPipeline(Array $options = null, $callable = null)
{
$pipeline = new PipelineContext($this, $options);
return $this->pipelineExecute($pipeline, $callable);
}
/**
* Executes a pipeline context when a callable object is passed.
*
* @param array $options Options of the context initialization.
* @param mixed $callable Optional callable object used to execute the context.
* @return PipelineContext|array
*/
private function pipelineExecute(PipelineContext $pipeline, $callable)
{
return isset($callable) ? $pipeline->execute($callable) : $pipeline;
}
/**
* Creates a new transaction context and returns it, or returns the results of
* a transaction executed inside the optionally provided callable object.
*
* @param mixed $arg,... Options for the context, a callable object, or both.
* @return MultiExecContext|array
*/
public function multiExec(/* arguments */)
{
return $this->sharedInitializer(func_get_args(), 'initMultiExec');
}
/**
* Transaction context initializer.
*
* @param array $options Options for the context.
* @param mixed $callable Optional callable object used to execute the context.
* @return MultiExecContext|array
*/
protected function initMultiExec(Array $options = null, $callable = null)
{
$transaction = new MultiExecContext($this, $options ?: array());
return isset($callable) ? $transaction->execute($callable) : $transaction;
}
/**
* Creates a new Publish / Subscribe context and returns it, or executes it
* inside the optionally provided callable object.
*
* @param mixed $arg,... Options for the context, a callable object, or both.
* @return MultiExecContext|array
*/
public function pubSub(/* arguments */)
{
return $this->sharedInitializer(func_get_args(), 'initPubSub');
}
/**
* Publish / Subscribe context initializer.
*
* @param array $options Options for the context.
* @param mixed $callable Optional callable object used to execute the context.
* @return PubSubContext
*/
protected function initPubSub(Array $options = null, $callable = null)
{
$pubsub = new PubSubContext($this, $options);
if (!isset($callable)) {
return $pubsub;
}
foreach ($pubsub as $message) {
if (call_user_func($callable, $pubsub, $message) === false) {
$pubsub->closeContext();
}
}
}
/**
* Returns a new monitor context.
*
* @return MonitorContext
*/
public function monitor()
{
return new MonitorContext($this);
}
}
+170
View File
@@ -0,0 +1,170 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Commands;
use Predis\Helpers;
use Predis\Distribution\INodeKeyGenerator;
/**
* Base class for Redis commands.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
abstract class Command implements ICommand
{
private $hash;
private $arguments = array();
/**
* Returns a filtered array of the arguments.
*
* @param array $arguments List of arguments.
* @return array
*/
protected function filterArguments(Array $arguments)
{
return $arguments;
}
/**
* {@inheritdoc}
*/
public function setArguments(Array $arguments)
{
$this->arguments = $this->filterArguments($arguments);
unset($this->hash);
}
/**
* Sets the arguments array without filtering.
*
* @param array $arguments List of arguments.
*/
public function setRawArguments(Array $arguments)
{
$this->arguments = $arguments;
unset($this->hash);
}
/**
* {@inheritdoc}
*/
public function getArguments()
{
return $this->arguments;
}
/**
* Gets the argument from the arguments list at the specified index.
*
* @param array $arguments Position of the argument.
*/
public function getArgument($index = 0)
{
if (isset($this->arguments[$index]) === true) {
return $this->arguments[$index];
}
}
/**
* Checks if the command can return an hash for client-side sharding.
*
* @return Boolean
*/
protected function canBeHashed()
{
return isset($this->arguments[0]);
}
/**
* Checks if the specified array of keys will generate the same hash.
*
* @param array $keys Array of keys.
* @return Boolean
*/
protected function checkSameHashForKeys(Array $keys)
{
if (($count = count($keys)) === 0) {
return false;
}
$currentKey = Helpers::extractKeyTag($keys[0]);
for ($i = 1; $i < $count; $i++) {
$nextKey = Helpers::extractKeyTag($keys[$i]);
if ($currentKey !== $nextKey) {
return false;
}
$currentKey = $nextKey;
}
return true;
}
/**
* {@inheritdoc}
*/
public function getHash(INodeKeyGenerator $distributor)
{
if (isset($this->hash)) {
return $this->hash;
}
if ($this->canBeHashed()) {
$key = Helpers::extractKeyTag($this->arguments[0]);
$this->hash = $distributor->generateKey($key);
return $this->hash;
}
return null;
}
/**
* {@inheritdoc}
*/
public function parseResponse($data)
{
return $data;
}
/**
* Helper function used to reduce a list of arguments to a string.
*
* @param string $accumulator Temporary string.
* @param string $argument Current argument.
* @return string
*/
protected function toStringArgumentReducer($accumulator, $argument)
{
if (strlen($argument) > 32) {
$argument = substr($argument, 0, 32) . '[...]';
}
$accumulator .= " $argument";
return $accumulator;
}
/**
* Returns a partial string representation of the command with its arguments.
*
* @return string
*/
public function __toString()
{
return array_reduce(
$this->getArguments(),
array($this, 'toStringArgumentReducer'),
$this->getId()
);
}
}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/auth
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ConnectionAuth extends Command
@@ -25,4 +24,12 @@ class ConnectionAuth extends Command
{
return 'AUTH';
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/echo
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ConnectionEcho extends Command
@@ -25,4 +24,12 @@ class ConnectionEcho extends Command
{
return 'ECHO';
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/ping
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ConnectionPing extends Command
@@ -25,4 +24,20 @@ class ConnectionPing extends Command
{
return 'PING';
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
/**
* {@inheritdoc}
*/
public function parseResponse($data)
{
return $data === 'PONG' ? true : false;
}
}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/quit
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ConnectionQuit extends Command
@@ -25,4 +24,12 @@ class ConnectionQuit extends Command
{
return 'QUIT';
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/select
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ConnectionSelect extends Command
@@ -25,4 +24,12 @@ class ConnectionSelect extends Command
{
return 'SELECT';
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
}
@@ -9,14 +9,15 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
use Predis\Helpers;
/**
* @link http://redis.io/commands/hdel
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashDelete extends Command
class HashDelete extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -29,8 +30,8 @@ class HashDelete extends Command
/**
* {@inheritdoc}
*/
protected function filterArguments(array $arguments)
protected function filterArguments(Array $arguments)
{
return self::normalizeVariadic($arguments);
return Helpers::filterVariadicValues($arguments);
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hexists
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashExists extends Command
class HashExists extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hget
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashGet extends Command
class HashGet extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,15 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
use Predis\Iterators\MultiBulkResponseTuple;
/**
* @link http://redis.io/commands/hgetall
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashGetAll extends Command
class HashGetAll extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -31,9 +32,12 @@ class HashGetAll extends Command
*/
public function parseResponse($data)
{
$result = array();
if ($data instanceof \Iterator) {
return new MultiBulkResponseTuple($data);
}
for ($i = 0; $i < count($data); ++$i) {
$result = array();
for ($i = 0; $i < count($data); $i++) {
$result[$data[$i]] = $data[++$i];
}
@@ -9,14 +9,15 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
use Predis\Helpers;
/**
* @link http://redis.io/commands/hmget
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashGetMultiple extends Command
class HashGetMultiple extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -29,8 +30,8 @@ class HashGetMultiple extends Command
/**
* {@inheritdoc}
*/
protected function filterArguments(array $arguments)
protected function filterArguments(Array $arguments)
{
return self::normalizeVariadic($arguments);
return Helpers::filterVariadicValues($arguments);
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hincrby
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashIncrementBy extends Command
class HashIncrementBy extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hincrbyfloat
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashIncrementByFloat extends Command
class HashIncrementByFloat extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hkeys
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashKeys extends Command
class HashKeys extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hlen
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashLength extends Command
class HashLength extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hset
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashSet extends Command
class HashSet extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hmset
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashSetMultiple extends Command
class HashSetMultiple extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -29,7 +28,7 @@ class HashSetMultiple extends Command
/**
* {@inheritdoc}
*/
protected function filterArguments(array $arguments)
protected function filterArguments(Array $arguments)
{
if (count($arguments) === 2 && is_array($arguments[1])) {
$flattenedKVs = array($arguments[0]);
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hsetnx
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashSetPreserve extends Command
class HashSetPreserve extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/hvals
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class HashValues extends Command
class HashValues extends PrefixableCommand
{
/**
* {@inheritdoc}
+59
View File
@@ -0,0 +1,59 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Commands;
use Predis\Distribution\INodeKeyGenerator;
/**
* Defines an abstraction representing a Redis command.
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
interface ICommand
{
/**
* Gets the ID of a Redis command.
*
* @return string
*/
public function getId();
/**
* Returns an hash of the command using the provided algorithm against the
* key (used to calculate the distribution of keys with client-side sharding).
*
* @param INodeKeyGenerator $distributor Distribution algorithm.
* @return int
*/
public function getHash(INodeKeyGenerator $distributor);
/**
* Sets the arguments of the command.
*
* @param array $arguments List of arguments.
*/
public function setArguments(Array $arguments);
/**
* Gets the arguments of the command.
*
* @return array
*/
public function getArguments();
/**
* Parses a reply buffer and returns a PHP object.
*
* @param string $data Binary string containing the whole reply.
* @return mixed
*/
public function parseResponse($data);
}
@@ -9,14 +9,16 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
use Predis\Distribution\INodeKeyGenerator;
/**
* Defines a command whose keys can be prefixed.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
interface PrefixableCommandInterface extends CommandInterface
interface IPrefixable
{
/**
* Prefixes all the keys found in the arguments of the command.
+58
View File
@@ -0,0 +1,58 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Commands;
use Predis\Helpers;
/**
* @link http://redis.io/commands/del
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyDelete extends Command implements IPrefixable
{
/**
* {@inheritdoc}
*/
public function getId()
{
return 'DEL';
}
/**
* {@inheritdoc}
*/
protected function filterArguments(Array $arguments)
{
return Helpers::filterArrayArguments($arguments);
}
/**
* {@inheritdoc}
*/
public function prefixKeys($prefix)
{
PrefixHelpers::all($this, $prefix);
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
$args = $this->getArguments();
if (count($args) === 1) {
return true;
}
return $this->checkSameHashForKeys($args);
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/exists
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyExists extends Command
class KeyExists extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/expire
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyExpire extends Command
class KeyExpire extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/expireat
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyExpireAt extends Command
class KeyExpireAt extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,28 +9,27 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/smove
*
* @link http://redis.io/commands/keys
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class SetMove extends Command
class KeyKeys extends PrefixableCommand
{
/**
* {@inheritdoc}
*/
public function getId()
{
return 'SMOVE';
return 'KEYS';
}
/**
* {@inheritdoc}
*/
public function parseResponse($data)
protected function canBeHashed()
{
return (bool) $data;
return false;
}
}
@@ -9,20 +9,20 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/keys
*
* @author Daniele Alessandri <suppakilla@gmail.com>
* @deprecated
*/
class KeyKeys extends Command
class KeyKeysV12x extends KeyKeys
{
/**
* {@inheritdoc}
*/
public function getId()
public function parseResponse($data)
{
return 'KEYS';
return explode(' ', $data);
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/move
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyMove extends Command
class KeyMove extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -26,6 +25,14 @@ class KeyMove extends Command
return 'MOVE';
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
/**
* {@inheritdoc}
*/
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/persist
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyPersist extends Command
class KeyPersist extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/pexpire
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyPreciseExpire extends KeyExpire
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/pexpireat
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyPreciseExpireAt extends KeyExpireAt
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/pttl
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyPreciseTimeToLive extends KeyTimeToLive
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/randomkey
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyRandom extends Command
@@ -26,6 +25,14 @@ class KeyRandom extends Command
return 'RANDOMKEY';
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
/**
* {@inheritdoc}
*/
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/rename
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyRename extends Command
class KeyRename extends Command implements IPrefixable
{
/**
* {@inheritdoc}
@@ -25,4 +24,20 @@ class KeyRename extends Command
{
return 'RENAME';
}
/**
* {@inheritdoc}
*/
public function prefixKeys($prefix)
{
PrefixHelpers::all($this, $prefix);
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return false;
}
}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/renamenx
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyRenamePreserve extends KeyRename
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/sort
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeySort extends Command
class KeySort extends Command implements IPrefixable
{
/**
* {@inheritdoc}
@@ -29,7 +28,7 @@ class KeySort extends Command
/**
* {@inheritdoc}
*/
protected function filterArguments(array $arguments)
protected function filterArguments(Array $arguments)
{
if (count($arguments) === 1) {
return $arguments;
@@ -45,21 +44,21 @@ class KeySort extends Command
if (isset($sortParams['GET'])) {
$getargs = $sortParams['GET'];
if (is_array($getargs)) {
foreach ($getargs as $getarg) {
$query[] = 'GET';
$query[] = $getarg;
}
} else {
}
else {
$query[] = 'GET';
$query[] = $getargs;
}
}
if (isset($sortParams['LIMIT']) &&
is_array($sortParams['LIMIT']) &&
count($sortParams['LIMIT']) == 2) {
if (isset($sortParams['LIMIT']) && is_array($sortParams['LIMIT'])
&& count($sortParams['LIMIT']) == 2) {
$query[] = 'LIMIT';
$query[] = $sortParams['LIMIT'][0];
$query[] = $sortParams['LIMIT'][1];
@@ -80,4 +79,37 @@ class KeySort extends Command
return $query;
}
/**
* {@inheritdoc}
*/
public function prefixKeys($prefix)
{
$arguments = $this->getArguments();
$arguments[0] = "$prefix{$arguments[0]}";
if (($count = count($arguments)) > 1) {
for ($i = 1; $i < $count; $i++) {
switch ($arguments[$i]) {
case 'BY':
case 'STORE':
$arguments[$i] = "$prefix{$arguments[++$i]}";
break;
case 'GET':
$value = $arguments[++$i];
if ($value !== '#') {
$arguments[$i] = "$prefix$value";
}
break;
case 'LIMIT';
$i += 2;
break;
}
}
}
$this->setRawArguments($arguments);
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/ttl
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyTimeToLive extends Command
class KeyTimeToLive extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/type
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class KeyType extends Command
class KeyType extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/lindex
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListIndex extends Command
class ListIndex extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/linsert
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListInsert extends Command
class ListInsert extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/llen
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListLength extends Command
class ListLength extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/lpop
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPopFirst extends Command
class ListPopFirst extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/blpop
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPopFirstBlocking extends Command
class ListPopFirstBlocking extends Command implements IPrefixable
{
/**
* {@inheritdoc}
@@ -29,13 +28,30 @@ class ListPopFirstBlocking extends Command
/**
* {@inheritdoc}
*/
protected function filterArguments(array $arguments)
protected function filterArguments(Array $arguments)
{
if (count($arguments) === 2 && is_array($arguments[0])) {
list($arguments, $timeout) = $arguments;
array_push($arguments, $timeout);
}
return $arguments;
}
/**
* {@inheritdoc}
*/
public function prefixKeys($prefix)
{
PrefixHelpers::skipLast($this, $prefix);
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return $this->checkSameHashForKeys(
array_slice(($args = $this->getArguments()), 0, count($args) - 1)
);
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/rpop
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPopLast extends Command
class ListPopLast extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/brpop
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPopLastBlocking extends ListPopFirstBlocking
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/rpoplpush
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPopLastPushHead extends Command
class ListPopLastPushHead extends Command implements IPrefixable
{
/**
* {@inheritdoc}
@@ -25,4 +24,20 @@ class ListPopLastPushHead extends Command
{
return 'RPOPLPUSH';
}
/**
* {@inheritdoc}
*/
public function prefixKeys($prefix)
{
PrefixHelpers::all($this, $prefix);
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return $this->checkSameHashForKeys($this->getArguments());
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/brpoplpush
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPopLastPushHeadBlocking extends Command
class ListPopLastPushHeadBlocking extends Command implements IPrefixable
{
/**
* {@inheritdoc}
@@ -25,4 +24,22 @@ class ListPopLastPushHeadBlocking extends Command
{
return 'BRPOPLPUSH';
}
/**
* {@inheritdoc}
*/
public function prefixKeys($prefix)
{
PrefixHelpers::skipLast($this, $prefix);
}
/**
* {@inheritdoc}
*/
protected function canBeHashed()
{
return $this->checkSameHashForKeys(
array_slice($args = $this->getArguments(), 0, count($args) - 1)
);
}
}
@@ -9,11 +9,10 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/lpush
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPushHead extends ListPushTail
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/lpushx
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPushHeadX extends Command
class ListPushHeadX extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,15 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
use Predis\Helpers;
/**
* @link http://redis.io/commands/rpush
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPushTail extends Command
class ListPushTail extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -29,8 +30,8 @@ class ListPushTail extends Command
/**
* {@inheritdoc}
*/
protected function filterArguments(array $arguments)
protected function filterArguments(Array $arguments)
{
return self::normalizeVariadic($arguments);
return Helpers::filterVariadicValues($arguments);
}
}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/rpushx
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListPushTailX extends Command
class ListPushTailX extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/lrange
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListRange extends Command
class ListRange extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/lrem
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListRemove extends Command
class ListRemove extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/lset
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListSet extends Command
class ListSet extends PrefixableCommand
{
/**
* {@inheritdoc}
@@ -9,14 +9,13 @@
* file that was distributed with this source code.
*/
namespace Predis\Command;
namespace Predis\Commands;
/**
* @link http://redis.io/commands/ltrim
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ListTrim extends Command
class ListTrim extends PrefixableCommand
{
/**
* {@inheritdoc}
+87
View File
@@ -0,0 +1,87 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Commands;
/**
* Class that defines a few helpers method for prefixing keys.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class PrefixHelpers
{
/**
* Applies the specified prefix only the first argument.
*
* @param ICommand $command Command instance.
* @param string $prefix Prefix string.
*/
public static function first(ICommand $command, $prefix)
{
if ($arguments = $command->getArguments()) {
$arguments[0] = "$prefix{$arguments[0]}";
$command->setRawArguments($arguments);
}
}
/**
* Applies the specified prefix to all the arguments.
*
* @param ICommand $command Command instance.
* @param string $prefix Prefix string.
*/
public static function all(ICommand $command, $prefix)
{
$arguments = $command->getArguments();
foreach ($arguments as &$key) {
$key = "$prefix$key";
}
$command->setRawArguments($arguments);
}
/**
* Applies the specified prefix only to even arguments in the list.
*
* @param ICommand $command Command instance.
* @param string $prefix Prefix string.
*/
public static function interleaved(ICommand $command, $prefix)
{
$arguments = $command->getArguments();
$length = count($arguments);
for ($i = 0; $i < $length; $i += 2) {
$arguments[$i] = "$prefix{$arguments[$i]}";
}
$command->setRawArguments($arguments);
}
/**
* Applies the specified prefix to all the arguments but the last one.
*
* @param ICommand $command Command instance.
* @param string $prefix Prefix string.
*/
public static function skipLast(ICommand $command, $prefix)
{
$arguments = $command->getArguments();
$length = count($arguments);
for ($i = 0; $i < $length - 1; $i++) {
$arguments[$i] = "$prefix{$arguments[$i]}";
}
$command->setRawArguments($arguments);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Commands;
/**
* Base class for Redis commands with prefixable keys.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
abstract class PrefixableCommand extends Command implements IPrefixable
{
/**
* {@inheritdoc}
*/
public function prefixKeys($prefix)
{
if ($arguments = $this->getArguments()) {
$arguments[0] = "$prefix{$arguments[0]}";
$this->setRawArguments($arguments);
}
}
}
@@ -0,0 +1,29 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Commands\Processors;
use Predis\Commands\ICommand;
/**
* A command processor processes commands before they are sent to Redis.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
interface ICommandProcessor
{
/**
* Processes a Redis command.
*
* @param ICommand $command Redis command.
*/
public function process(ICommand $command);
}

Some files were not shown because too many files have changed in this diff Show More