guzzle-iterators.rst 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. ================
  2. Guzzle iterators
  3. ================
  4. Guzzle provides several SPL iterators that can be used with other SPL iterators, including Guzzle resource iterators.
  5. Guzzle's ``guzzle/iterator`` component can also be used independently of the rest of Guzzle through Packagist and
  6. Composer: https://packagist.org/packages/guzzle/iterator
  7. ChunkedIterator
  8. ---------------
  9. Pulls out multiple values from an inner iterator and yields and array of values for each outer iteration -- essentially
  10. pulling out chunks of values from the inner iterator.
  11. .. code-block:: php
  12. use Guzzle\Iterator\ChunkedIterator;
  13. $inner = new ArrayIterator(range(0, 8));
  14. $chunkedIterator = new ChunkedIterator($inner, 2);
  15. foreach ($chunkedIterator as $chunk) {
  16. echo implode(', ', $chunk) . "\n";
  17. }
  18. // >>> 0, 1
  19. // >>> 2, 3
  20. // >>> 4, 5
  21. // >>> 6, 7
  22. // >>> 8
  23. FilterIterator
  24. --------------
  25. This iterator is used to filter values out of the inner iterator. This iterator can be used when PHP 5.4's
  26. CallbackFilterIterator is not available.
  27. .. code-block:: php
  28. use Guzzle\Iterator\FilterIterator;
  29. $inner = new ArrayIterator(range(1, 10));
  30. $filterIterator = new FilterIterator($inner, function ($value) {
  31. return $value % 2;
  32. });
  33. foreach ($filterIterator as $value) {
  34. echo $value . "\n";
  35. }
  36. // >>> 2
  37. // >>> 4
  38. // >>> 6
  39. // >>> 8
  40. // >>> 10
  41. MapIterator
  42. -----------
  43. This iterator modifies the values of the inner iterator before yielding.
  44. .. code-block:: php
  45. use Guzzle\Iterator\MapIterator;
  46. $inner = new ArrayIterator(range(0, 3));
  47. $mapIterator = new MapIterator($inner, function ($value) {
  48. return $value * 10;
  49. });
  50. foreach ($mapIterator as $value) {
  51. echo $value . "\n";
  52. }
  53. // >>> 0
  54. // >>> 10
  55. // >>> 20
  56. // >>> 30
  57. MethodProxyIterator
  58. -------------------
  59. This decorator is useful when you need to expose a specific method from an inner iterator that might be wrapper
  60. by one or more iterator decorators. This decorator proxies missing method calls to each inner iterator until one
  61. of the inner iterators can fulfill the call.
  62. .. code-block:: php
  63. use Guzzle\Iterator\MethodProxyIterator;
  64. $inner = new \ArrayIterator();
  65. $proxy = new MethodProxyIterator($inner);
  66. // Proxy method calls to the ArrayIterator
  67. $proxy->append('a');
  68. $proxy->append('b');