MultiBulkReplyIterators.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. require 'SharedConfigurations.php';
  11. // Operations such as LRANGE, ZRANGE and others can potentially generate replies
  12. // containing a huge number of items. In some corner cases, such replies might
  13. // end up exhausting the maximum allowed memory allocated for a PHP process.
  14. // Multibulk iterators can be handy because they allow you to stream multibulk
  15. // replies using plain old PHP iterators, making it possible to iterate them with
  16. // a classic `foreach` loop and avoiding to consume an excessive amount of memory.
  17. //
  18. // PS: please note that multibulk iterators are supported only by the standard
  19. // connection backend class (Predis\Connection\StreamConnection) and not the
  20. // phpiredis-based one (Predis\Connection\PhpiredisConnection).
  21. // Create a client and force the connection to use iterable multibulk responses.
  22. $client = new Predis\Client($single_server + array('iterable_multibulk' => true));
  23. // Prepare an hash with some fields and their respective values.
  24. $client->hmset('metavars', array('foo' => 'bar', 'hoge' => 'piyo', 'lol' => 'wut'));
  25. // By default multibulk iterators iterate over the reply as a list of items...
  26. foreach ($client->hgetall('metavars') as $index => $item) {
  27. echo "[$index] $item\n";
  28. }
  29. /* OUTPUT:
  30. [0] foo
  31. [1] bar
  32. [2] hoge
  33. [3] piyo
  34. [4] lol
  35. [5] wut
  36. */
  37. // ... but certain multibulk replies are better represented as lists of tuples.
  38. foreach ($client->hgetall('metavars')->asTuple() as $index => $kv) {
  39. list($key, $value) = $kv;
  40. echo "[$index] $key => $value\n";
  41. }
  42. /* OUTPUT:
  43. [0] foo => bar
  44. [1] hoge => piyo
  45. [2] lol => wut
  46. */