{"id":13609221,"url":"https://github.com/predis/predis","last_synced_at":"2025-05-12T20:42:56.540Z","repository":{"id":717253,"uuid":"364315","full_name":"predis/predis","owner":"predis","description":"A flexible and feature-complete Redis/Valkey client for PHP.","archived":false,"fork":false,"pushed_at":"2025-05-12T16:00:40.000Z","size":8610,"stargazers_count":7684,"open_issues_count":50,"forks_count":991,"subscribers_count":210,"default_branch":"main","last_synced_at":"2025-05-12T17:23:26.749Z","etag":null,"topics":["php","predis","redis","redis-cluster","redis-sentinel"],"latest_commit_sha":null,"homepage":"https://github.com/predis/predis/wiki","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/predis.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":".github/CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"tillkruss","custom":"https://www.paypal.me/tillkruss"}},"created_at":"2009-11-07T11:27:33.000Z","updated_at":"2025-05-12T16:00:46.000Z","dependencies_parsed_at":"2023-09-26T20:08:54.390Z","dependency_job_id":"4cb29839-5de5-4c25-ac6f-259321ab3f11","html_url":"https://github.com/predis/predis","commit_stats":{"total_commits":2182,"total_committers":103,"mean_commits":"21.184466019417474","dds":"0.16269477543538036","last_synced_commit":"0a92618fa14f7fb7a8fc9de7564bed69cebb97e9"},"previous_names":["nrk/predis"],"tags_count":64,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/predis%2Fpredis","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/predis%2Fpredis/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/predis%2Fpredis/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/predis%2Fpredis/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/predis","download_url":"https://codeload.github.com/predis/predis/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253818075,"owners_count":21969106,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["php","predis","redis","redis-cluster","redis-sentinel"],"created_at":"2024-08-01T19:01:33.386Z","updated_at":"2025-05-12T20:42:56.533Z","avatar_url":"https://github.com/predis.png","language":"PHP","readme":"# Predis #\n\n[![Software license][ico-license]](LICENSE)\n[![Latest stable][ico-version-stable]][link-releases]\n[![Latest development][ico-version-dev]][link-releases]\n[![Monthly installs][ico-downloads-monthly]][link-downloads]\n[![Build status][ico-build]][link-actions]\n[![Coverage Status][ico-coverage]][link-coverage]\n\nA flexible and feature-complete [Redis](http://redis.io) / [Valkey](https://github.com/valkey-io/valkey) client for PHP 7.2 and newer.\n\nMore details about this project can be found on the [frequently asked questions](FAQ.md).\n\n\n## Main features ##\n\n- Support for Redis from __3.0__ to __8.0__.\n- Support for clustering using client-side sharding and pluggable keyspace distributors.\n- Support for [redis-cluster](http://redis.io/topics/cluster-tutorial) (Redis \u003e= 3.0).\n- Support for master-slave replication setups and [redis-sentinel](http://redis.io/topics/sentinel).\n- Transparent key prefixing of keys using a customizable prefix strategy.\n- Command pipelining on both single nodes and clusters (client-side sharding only).\n- Abstraction for Redis transactions (Redis \u003e= 2.0) and CAS operations (Redis \u003e= 2.2).\n- Abstraction for Lua scripting (Redis \u003e= 2.6) and automatic switching between `EVALSHA` or `EVAL`.\n- Abstraction for `SCAN`, `SSCAN`, `ZSCAN` and `HSCAN` (Redis \u003e= 2.8) based on PHP iterators.\n- Connections are established lazily by the client upon the first command and can be persisted.\n- Connections can be established via TCP/IP (also TLS/SSL-encrypted) or UNIX domain sockets.\n- Support for custom connection classes for providing different network or protocol backends.\n- Flexible system for defining custom commands and override the default ones.\n\n\n## How to _install_ and use Predis ##\n\nThis library can be found on [Packagist](http://packagist.org/packages/predis/predis) for an easier\nmanagement of projects dependencies using [Composer](http://packagist.org/about-composer).\nCompressed archives of each release are [available on GitHub](https://github.com/predis/predis/releases).\n\n```shell\ncomposer require predis/predis\n```\n\n\n### Loading the library ###\n\nPredis relies on the autoloading features of PHP to load its files when needed and complies with the\n[PSR-4 standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md).\nAutoloading is handled automatically when dependencies are managed through Composer, but it is also\npossible to leverage its own autoloader in projects or scripts lacking any autoload facility:\n\n```php\n// Prepend a base path if Predis is not available in your \"include_path\".\nrequire 'Predis/Autoloader.php';\n\nPredis\\Autoloader::register();\n```\n\n\n### Connecting to Redis ###\n\nWhen creating a client instance without passing any connection parameter, Predis assumes `127.0.0.1`\nand `6379` as default host and port. The default timeout for the `connect()` operation is 5 seconds:\n\n```php\n$client = new Predis\\Client();\n$client-\u003eset('foo', 'bar');\n$value = $client-\u003eget('foo');\n```\n\nConnection parameters can be supplied either in the form of URI strings or named arrays. The latter\nis the preferred way to supply parameters, but URI strings can be useful when parameters are read\nfrom non-structured or partially-structured sources:\n\n```php\n// Parameters passed using a named array:\n$client = new Predis\\Client([\n    'scheme' =\u003e 'tcp',\n    'host'   =\u003e '10.0.0.1',\n    'port'   =\u003e 6379,\n]);\n\n// Same set of parameters, passed using an URI string:\n$client = new Predis\\Client('tcp://10.0.0.1:6379');\n```\n\nPassword protected servers can be accessed by adding `password` to the parameters set. When ACLs are\nenabled on Redis \u003e= 6.0, both `username` and `password` are required for user authentication.\n\nIt is also possible to connect to local instances of Redis using UNIX domain sockets, in this case\nthe parameters must use the `unix` scheme and specify a path for the socket file:\n\n```php\n$client = new Predis\\Client(['scheme' =\u003e 'unix', 'path' =\u003e '/path/to/redis.sock']);\n$client = new Predis\\Client('unix:/path/to/redis.sock');\n```\n\nThe client can leverage TLS/SSL encryption to connect to secured remote Redis instances without the\nneed to configure an SSL proxy like stunnel. This can be useful when connecting to nodes running on\nvarious cloud hosting providers. Encryption can be enabled with using the `tls` scheme and an array\nof suitable [options](http://php.net/manual/context.ssl.php) passed via the `ssl` parameter:\n\n```php\n// Named array of connection parameters:\n$client = new Predis\\Client([\n  'scheme' =\u003e 'tls',\n  'ssl'    =\u003e ['cafile' =\u003e 'private.pem', 'verify_peer' =\u003e true],\n]);\n\n// Same set of parameters, but using an URI string:\n$client = new Predis\\Client('tls://127.0.0.1?ssl[cafile]=private.pem\u0026ssl[verify_peer]=1');\n```\n\nThe connection schemes [`redis`](http://www.iana.org/assignments/uri-schemes/prov/redis) (alias of\n`tcp`) and [`rediss`](http://www.iana.org/assignments/uri-schemes/prov/rediss) (alias of `tls`) are\nalso supported, with the difference that URI strings containing these schemes are parsed following\nthe rules described on their respective IANA provisional registration documents.\n\nThe actual list of supported connection parameters can vary depending on each connection backend so\nit is recommended to refer to their specific documentation or implementation for details.\n\nPredis can aggregate multiple connections when providing an array of connection parameters and the\nappropriate option to instruct the client about how to aggregate them (clustering, replication or a\ncustom aggregation logic). Named arrays and URI strings can be mixed when providing configurations\nfor each node:\n\n```php\n$client = new Predis\\Client([\n    'tcp://10.0.0.1?alias=first-node', ['host' =\u003e '10.0.0.2', 'alias' =\u003e 'second-node'],\n], [\n    'cluster' =\u003e 'predis',\n]);\n```\n\nSee the [aggregate connections](#aggregate-connections) section of this document for more details.\n\nConnections to Redis are lazy meaning that the client connects to a server only if and when needed.\nWhile it is recommended to let the client do its own stuff under the hood, there may be times when\nit is still desired to have control of when the connection is opened or closed: this can easily be\nachieved by invoking `$client-\u003econnect()` and `$client-\u003edisconnect()`. Please note that the effect\nof these methods on aggregate connections may differ depending on each specific implementation.\n\n\n### Client configuration ###\n\nMany aspects and behaviors of the client can be configured by passing specific client options to the\nsecond argument of `Predis\\Client::__construct()`:\n\n```php\n$client = new Predis\\Client($parameters, ['prefix' =\u003e 'sample:']);\n```\n\nOptions are managed using a mini DI-alike container and their values can be lazily initialized only\nwhen needed. The client options supported by default in Predis are:\n\n  - `prefix`: prefix string applied to every key found in commands.\n  - `exceptions`: whether the client should throw or return responses upon Redis errors.\n  - `connections`: list of connection backends or a connection factory instance.\n  - `cluster`: specifies a cluster backend (`predis`, `redis` or callable).\n  - `replication`: specifies a replication backend (`predis`, `sentinel` or callable).\n  - `aggregate`: configures the client with a custom aggregate connection (callable).\n  - `parameters`: list of default connection parameters for aggregate connections.\n  - `commands`: specifies a command factory instance to use through the library.\n  - `readTimeout`: (cluster only) Timeout between read operations while loop over connections.\n\nUsers can also provide custom options with values or callable objects (for lazy initialization) that\nare stored in the options container for later use through the library.\n\n\n### Aggregate connections ###\n\nAggregate connections are the foundation upon which Predis implements clustering and replication and\nthey are used to group multiple connections to single Redis nodes and hide the specific logic needed\nto handle them properly depending on the context. Aggregate connections usually require an array of\nconnection parameters along with the appropriate client option when creating a new client instance.\n\n#### Cluster ####\n\nPredis can be configured to work in clustering mode with a traditional client-side sharding approach\nto create a cluster of independent nodes and distribute the keyspace among them. This approach needs\nsome sort of external health monitoring of nodes and requires the keyspace to be rebalanced manually\nwhen nodes are added or removed:\n\n```php\n$parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3'];\n$options    = ['cluster' =\u003e 'predis'];\n\n$client = new Predis\\Client($parameters);\n```\n\nAlong with Redis 3.0, a new supervised and coordinated type of clustering was introduced in the form\nof [redis-cluster](http://redis.io/topics/cluster-tutorial). This kind of approach uses a different\nalgorithm to distribute the keyspaces, with Redis nodes coordinating themselves by communicating via\na gossip protocol to handle health status, rebalancing, nodes discovery and request redirection. In\norder to connect to a cluster managed by redis-cluster, the client requires a list of its nodes (not\nnecessarily complete since it will automatically discover new nodes if necessary) and the `cluster`\nclient options set to `redis`:\n\n```php\n$parameters = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3'];\n$options    = ['cluster' =\u003e 'redis'];\n\n$client = new Predis\\Client($parameters, $options);\n```\n\n#### Redis Gears with cluster ####\n\nSince Redis v7.2, Redis Gears module is a part of Redis Stack bundle. Client supports a variety of\nRedis Gears commands that can be used with OSS cluster API. Currently, before using any Redis\nGears commands against OSS cluster Redis server needs to be aware of cluster topology.\n\n`REDISGEARS_2.REFRESHCLUSTER` command should be called against **each master node** (read replicas\nshould be ignored) **on cluster creation and each time cluster topology changes**.\n\nIn most cases this actions should be performed from the CLI interface by the administrator, DevOPS\nor even Kubernetes, depends on your infrastructure managing process. However, client provides an API\nto do this programmatically.\n\n```php\n/** @var \\Predis\\Connection\\Cluster\\ClusterInterface $connection */\n$connection-\u003eexecuteCommandOnEachNode(\n    new \\Predis\\Command\\RawCommand('REDISGEARS_2.REFRESHCLUSTER')\n);\n```\n\n#### Replication ####\n\nThe client can be configured to operate in a single master / multiple slaves setup to provide better\nservice availability. When using replication, Predis recognizes read-only commands and sends them to\na random slave in order to provide some sort of load-balancing and switches to the master as soon as\nit detects a command that performs any kind of operation that would end up modifying the keyspace or\nthe value of a key. Instead of raising a connection error when a slave fails, the client attempts to\nfall back to a different slave among the ones provided in the configuration.\n\nThe basic configuration needed to use the client in replication mode requires one Redis server to be\nidentified as the master (this can be done via connection parameters by setting the `role` parameter\nto `master`) and one or more slaves (in this case setting `role` to `slave` for slaves is optional):\n\n```php\n$parameters = ['tcp://10.0.0.1?role=master', 'tcp://10.0.0.2', 'tcp://10.0.0.3'];\n$options    = ['replication' =\u003e 'predis'];\n\n$client = new Predis\\Client($parameters, $options);\n```\n\nThe above configuration has a static list of servers and relies entirely on the client's logic, but\nit is possible to rely on [`redis-sentinel`](http://redis.io/topics/sentinel) for a more robust HA\nenvironment with sentinel servers acting as a source of authority for clients for service discovery.\nThe minimum configuration required by the client to work with redis-sentinel is a list of connection\nparameters pointing to a bunch of sentinel instances, the `replication` option set to `sentinel` and\nthe `service` option set to the name of the service:\n\n```php\n$sentinels = ['tcp://10.0.0.1', 'tcp://10.0.0.2', 'tcp://10.0.0.3'];\n$options   = ['replication' =\u003e 'sentinel', 'service' =\u003e 'mymaster'];\n\n$client = new Predis\\Client($sentinels, $options);\n```\n\nIf the master and slave nodes are configured to require an authentication from clients, a password\nmust be provided via the global `parameters` client option. This option can also be used to specify\na different database index. The client options array would then look like this:\n\n```php\n$options = [\n    'replication' =\u003e 'sentinel',\n    'service' =\u003e 'mymaster',\n    'parameters' =\u003e [\n        'password' =\u003e $secretpassword,\n        'database' =\u003e 10,\n    ],\n];\n```\n\nWhile Predis is able to distinguish commands performing write and read-only operations, `EVAL` and\n`EVALSHA` represent a corner case in which the client switches to the master node because it cannot\ntell when a Lua script is safe to be executed on slaves. While this is indeed the default behavior,\nwhen certain Lua scripts do not perform write operations it is possible to provide an hint to tell\nthe client to stick with slaves for their execution:\n\n```php\n$parameters = ['tcp://10.0.0.1?role=master', 'tcp://10.0.0.2', 'tcp://10.0.0.3'];\n$options    = ['replication' =\u003e function () {\n    // Set scripts that won't trigger a switch from a slave to the master node.\n    $strategy = new Predis\\Replication\\ReplicationStrategy();\n    $strategy-\u003esetScriptReadOnly($LUA_SCRIPT);\n\n    return new Predis\\Connection\\Replication\\MasterSlaveReplication($strategy);\n}];\n\n$client = new Predis\\Client($parameters, $options);\n$client-\u003eeval($LUA_SCRIPT, 0);             // Sticks to slave using `eval`...\n$client-\u003eevalsha(sha1($LUA_SCRIPT), 0);    // ... and `evalsha`, too.\n```\n\nThe [`examples`](examples/) directory contains a few scripts that demonstrate how the client can be\nconfigured and used to leverage replication in both basic and complex scenarios.\n\n\n### Command pipelines ###\n\nPipelining can help with performances when many commands need to be sent to a server by reducing the\nlatency introduced by network round-trip timings. Pipelining also works with aggregate connections.\nThe client can execute the pipeline inside a callable block or return a pipeline instance with the\nability to chain commands thanks to its fluent interface:\n\n```php\n// Executes a pipeline inside the given callable block:\n$responses = $client-\u003epipeline(function ($pipe) {\n    for ($i = 0; $i \u003c 1000; $i++) {\n        $pipe-\u003eset(\"key:$i\", str_pad($i, 4, '0', 0));\n        $pipe-\u003eget(\"key:$i\");\n    }\n});\n\n// Returns a pipeline that can be chained thanks to its fluent interface:\n$responses = $client-\u003epipeline()-\u003eset('foo', 'bar')-\u003eget('foo')-\u003eexecute();\n```\n\n\n### Transactions ###\n\nThe client provides an abstraction for Redis transactions based on `MULTI` and `EXEC` with a similar\ninterface to command pipelines:\n\n```php\n// Executes a transaction inside the given callable block:\n$responses = $client-\u003etransaction(function ($tx) {\n    $tx-\u003eset('foo', 'bar');\n    $tx-\u003eget('foo');\n});\n\n// Returns a transaction that can be chained thanks to its fluent interface:\n$responses = $client-\u003etransaction()-\u003eset('foo', 'bar')-\u003eget('foo')-\u003eexecute();\n```\n\nThis abstraction can perform check-and-set operations thanks to `WATCH` and `UNWATCH` and provides\nautomatic retries of transactions aborted by Redis when `WATCH`ed keys are touched. For an example\nof a transaction using CAS you can see [the following example](examples/transaction_using_cas.php).\n\n#### Support for clustered connections ####\n\nSince Predis v3.0 transactions could be used with clustered connections. However, it has some limitations due to the\nfact that Redis doesn't support distributed transactions. All keys in the transaction context should operate on the same\nhash slot, due to this limitation it's recommended to use `{}` syntax to make sure that all keys will be mapped to the same hash\nslot. Apart from it no additional configuration needed on a client side.\n\n```php\n$redis = $this-\u003egetClient();\n\n$response = $redis-\u003etransaction(function (MultiExec $tx) {\n    $tx-\u003eset('{foo}foo', 'value');\n    $tx-\u003eset('{foo}bar', 'value');\n    $tx-\u003eset('{foo}baz', 'value');\n});\n\n// ['OK', 'OK', 'OK']\n```\n\n\n### Adding new commands ###\n\nWhile we try to update Predis to stay up to date with all the commands available in Redis, you might\nprefer to stick with an old version of the library or provide a different way to filter arguments or\nparse responses for specific commands. To achieve that, Predis provides the ability to implement new\ncommand classes to define or override commands in the default command factory used by the client:\n\n```php\n// Define a new command by extending Predis\\Command\\Command:\nclass BrandNewRedisCommand extends Predis\\Command\\Command\n{\n    public function getId()\n    {\n        return 'NEWCMD';\n    }\n}\n\n// Inject your command in the current command factory:\n$client = new Predis\\Client($parameters, [\n    'commands' =\u003e [\n        'newcmd' =\u003e 'BrandNewRedisCommand',\n    ],\n]);\n\n$response = $client-\u003enewcmd();\n```\n\nThere is also a method to send raw commands without filtering their arguments or parsing responses.\nUsers must provide the list of arguments for the command as an array, following the signatures as\ndefined by the [Redis documentation for commands](http://redis.io/commands):\n\n```php\n$response = $client-\u003eexecuteRaw(['SET', 'foo', 'bar']);\n```\n\n\n### Script commands ###\n\nWhile it is possible to leverage [Lua scripting](http://redis.io/commands/eval) on Redis 2.6+ using\ndirectly [`EVAL`](http://redis.io/commands/eval) and [`EVALSHA`](http://redis.io/commands/evalsha),\nPredis offers script commands as an higher level abstraction built upon them to make things simple.\nScript commands can be registered in the command factory used by the client and are accessible as if\nthey were plain Redis commands, but they define Lua scripts that get transmitted to the server for\nremote execution. Internally they use [`EVALSHA`](http://redis.io/commands/evalsha) by default and\nidentify a script by its SHA1 hash to save bandwidth, but [`EVAL`](http://redis.io/commands/eval)\nis used as a fall back when needed:\n\n```php\n// Define a new script command by extending Predis\\Command\\ScriptCommand:\nclass ListPushRandomValue extends Predis\\Command\\ScriptCommand\n{\n    public function getKeysCount()\n    {\n        return 1;\n    }\n\n    public function getScript()\n    {\n        return \u003c\u003c\u003cLUA\nmath.randomseed(ARGV[1])\nlocal rnd = tostring(math.random())\nredis.call('lpush', KEYS[1], rnd)\nreturn rnd\nLUA;\n    }\n}\n\n// Inject the script command in the current command factory:\n$client = new Predis\\Client($parameters, [\n    'commands' =\u003e [\n        'lpushrand' =\u003e 'ListPushRandomValue',\n    ],\n]);\n\n$response = $client-\u003elpushrand('random_values', $seed = mt_rand());\n```\n\n\n### Customizable connection backends ###\n\nPredis can use different connection backends to connect to Redis. The builtin Relay integration\nleverages the [Relay](https://github.com/cachewerk/relay) extension for PHP for major performance\ngains, by caching a partial replica of the Redis dataset in PHP shared runtime memory.\n\n```php\n$client = new Predis\\Client('tcp://127.0.0.1', [\n    'connections' =\u003e 'relay',\n]);\n```\n\nDevelopers can create their own connection classes to support whole new network backends, extend\nexisting classes or provide completely different implementations. Connection classes must implement\n`Predis\\Connection\\NodeConnectionInterface` or extend `Predis\\Connection\\AbstractConnection`:\n\n```php\nclass MyConnectionClass implements Predis\\Connection\\NodeConnectionInterface\n{\n    // Implementation goes here...\n}\n\n// Use MyConnectionClass to handle connections for the `tcp` scheme:\n$client = new Predis\\Client('tcp://127.0.0.1', [\n    'connections' =\u003e ['tcp' =\u003e 'MyConnectionClass'],\n]);\n```\n\nFor a more in-depth insight on how to create new connection backends you can refer to the actual\nimplementation of the standard connection classes available in the `Predis\\Connection` namespace.\n\n## RESP3 ##\n\n### Connection ###\nTo establish the connection using the [RESP3](https://github.com/redis/redis-specifications/blob/master/protocol/RESP3.md) protocol, you need to set parameter `protocol =\u003e 3`. The default protocol is RESP2.\n\nYou can pass parameter as configuration option in array or as a query parameter in `redis_url`\n\n```php\n  // Configuration option\n  $client = new \\Predis\\Client(['protocol' =\u003e 3]);\n\n  // Redis URL\n  $client = new \\Predis\\Client('redis://localhost:6379?protocol=3');\n\n  // [\"proto\" =\u003e \"3\"]\n  $client-\u003eexecuteRaw(['HELLO']);\n```\n\n### Command responses ###\nRESP3 protocol introduce a variety of new [response types](https://github.com/redis/redis-specifications/blob/master/protocol/RESP3.md#resp3-types),\nso on the client-side we have more explicit understanding on data types we retrieve from server. Here's some examples to show the difference\nbetween RESP2 and RESP3 responses.\n\n#### Float responses ####\n``` php\n// RESP2 connection\n$client = new \\Predis\\Client();\n\n$client-\u003egeoadd('my_geo', 11.111, 22.222, 'member1');\n\n// [[0 =\u003e string(20) \"11.11099988222122192\", 1 =\u003e string(20) \"22.22200052541037252\"]]\n// RESP2 returns float values as simple strings.\nvar_dump($client-\u003egeopos('my_geo', ['member1']));\n\n// RESP3 connection\n$client = new \\Predis\\Client(['protocol' =\u003e 3]);\n\n// [[0 =\u003e float(11.110999882221222), 1 =\u003e float(22.222000525410373)]]\n// RESP3 introduces new double type, that corresponds to PHP float.\nvar_dump($client-\u003egeopos('my_geo', ['member1']));\n```\n\n#### Aggregate types ####\nIn RESP3 new aggregate type [Map](https://github.com/redis/redis-specifications/blob/master/protocol/RESP3.md#map-type)\nwas introduced, that represents the sequence of field-value pairs. So it simplifies parsing, since we don't need to specify\nparsing strategy per command (RESP2) and instead relies on the type defined by protocol (RESP3).\n\nIn most cases RESP2 responses shouldn't differ from RESP3, since we added additional parsing for those\ncommand that return field-value pairs. However, since RESP2 requires additional parsing, it could be that some commands\nhad lack of it and return unhandled responses. In this case there would be difference like this:\n\n```php\n$client = new \\Predis\\Client();\n\n// RESP2: ['field', 'value]\n$client-\u003ecommandThatReturnsFieldValuePair('key');\n\n$client = new \\Predis\\Client(['protocol' =\u003e 3]);\n\n// RESP3: ['field' =\u003e 'value]\n$client-\u003ecommandThatReturnsFieldValuePair('key');\n```\n\nFeel free to open PR or GitHub issue if you face those protocol mismatching.\n\n### Push notifications ###\nRESP3 introduce a concept of [push connection](https://github.com/redis/redis-specifications/blob/master/protocol/RESP3.md#push-type),\nis the one where server could send asynchronous data to client which was not explicitly requested. Predis 3.0 provides\nan API to establish this kind of connection as separate blocking process (worker) and invoke callbacks depends on push\nnotification message type.\n\n#### Consumer ####\nFirst of all, you need to set up a consumer connection and provide an optional callback that will be executed before\nevent loop will be started. It allows you to subscribe on channels, enable keys invalidations tracking or enable monitor\nconnection, any Redis command to let server know that you want to receive push notification within this connection.\n\n```php\n// Make sure that RESP3 protocol enabled and read_write_timeout set 0,\n// so connection won't be killed by timeout.\n$client = new Predis\\Client(['read_write_timeout' =\u003e 0, 'protocol' =\u003e 3]);\n\n// Create push notifications consumer.\n// Provides callback where current consumer subscribes to few channels before\n// enter the loop.\n$push = $client-\u003epush(static function (ClientInterface $client) {\n    $response = $client-\u003esubscribe('channel', 'control');\n    $status = ($response[2] === 1) ? 'OK' : 'FAILED';\n    echo \"Channel subscription status: {$status}\\n\";\n});\n```\n\n#### Dispatcher loop ####\nDispatcher object allows you to attach a callback to given push notification type and run the actual worker process that\nlisten for incoming push notifications. To be able to stop blocking process in runtime you can specify a condition and\ncall `$dispatcher-\u003estop()` method from given callback. In this example we're waiting for specific message `terminate`\nwithin `control` channel that we subscribed to before entering the loop.\n\n```php\n// Storage for incoming notifications.\n$messages = [];\n\n// Create dispatcher for push notifications.\n$dispatcher = new Predis\\Consumer\\Push\\DispatcherLoop($push);\n\n$dispatcher-\u003eattachCallback(\n    PushResponseInterface::MESSAGE_DATA_TYPE,\n    static function (array $payload, DispatcherLoopInterface $dispatcher) {\n        global $messages;\n        [$channel, $message] = $payload;\n\n        if ($channel === 'control' \u0026\u0026 $message === 'terminate') {\n            echo \"Terminating notification consumer.\\n\";\n            $dispatcher-\u003estop();\n\n            return;\n        }\n\n        $messages[] = $message;\n        echo \"Received message: {$message}\\n\";\n    }\n);\n\n// Run consumer loop with attached callbacks.\n$dispatcher-\u003erun();\n\n// Count all messages that were received during consumer loop.\n$messagesCount = count($messages);\necho \"We received: {$messagesCount} messages\\n\";\n```\n\nThis example shows a simple script to count all incoming messages from push notifications that we receive from\nsubscribed channels until stop condition will be met. Examples available in `examples/` folder.\n\n### Sharded pub/sub ###\nFrom Redis 7.0, sharded Pub/Sub is introduced in which shard channels are assigned to slots by the same algorithm used\nto assign keys to slots.\n\nPredis 3.0 provides an API that allows to use pub/sub for Cluster connections using sharded pub/sub from Redis.\nYou don't need to specify any additional configuration to enable sharded pub/sub, it will be automatically enabled if\nCluster connection is using.\n\nImplementation looks pretty much the same as Push notification, so you need to set up consumer\nand run it over Dispatcher loop object. All examples available in `examples/` folder.\n## Development ##\n\n\n### Reporting bugs and contributing code ###\n\nContributions to Predis are highly appreciated either in the form of pull requests for new features,\nbug fixes, or just bug reports. We only ask you to adhere to issue and pull request templates.\n\n\n### Test suite ###\n\n__ATTENTION__: Do not ever run the test suite shipped with Predis against instances of Redis running\nin production environments or containing data you are interested in!\n\nPredis has a comprehensive test suite covering every aspect of the library and that can optionally\nperform integration tests against a running instance of Redis (required \u003e= 2.4.0 in order to verify\nthe correct behavior of the implementation of each command. Integration tests for unsupported Redis\ncommands are automatically skipped. If you do not have Redis up and running, integration tests can\nbe disabled. See [the tests README](tests/README.md) for more details about testing this library.\n\nPredis uses GitHub Actions for continuous integration and the history for past and current builds can be\nfound [on its actions page](https://github.com/predis/predis/actions).\n\n### License ###\n\nThe code for Predis is distributed under the terms of the MIT license (see [LICENSE](LICENSE)).\n\n[ico-license]: https://img.shields.io/github/license/predis/predis.svg?style=flat-square\n[ico-version-stable]: https://img.shields.io/github/v/tag/predis/predis?label=stable\u0026style=flat-square\n[ico-version-dev]: https://img.shields.io/github/v/tag/predis/predis?include_prereleases\u0026label=pre-release\u0026style=flat-square\n[ico-downloads-monthly]: https://img.shields.io/packagist/dm/predis/predis.svg?style=flat-square\n[ico-build]: https://img.shields.io/github/actions/workflow/status/predis/predis/tests.yml?branch=main\u0026style=flat-square\n[ico-coverage]: https://img.shields.io/coverallsCoverage/github/predis/predis?style=flat-square\n\n[link-releases]: https://github.com/predis/predis/releases\n[link-actions]: https://github.com/predis/predis/actions\n[link-downloads]: https://packagist.org/packages/predis/predis/stats\n[link-coverage]: https://coveralls.io/github/predis/predis\n","funding_links":["https://github.com/sponsors/tillkruss","https://www.paypal.me/tillkruss"],"categories":["PHP","目录","Table of Contents"],"sub_categories":["NoSQL"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpredis%2Fpredis","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpredis%2Fpredis","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpredis%2Fpredis/lists"}