Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Iter Laravel Package

php-standard-library/iter

Inspect and reduce any PHP iterable (arrays, generators, iterators) with small, focused helpers from PHP Standard Library - Iter. Designed for common iteration tasks and consistent behavior across iterable types.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require php-standard-library/iter
    

    No configuration required—just autoload via Composer.

  2. First Use Case: Replace a manual foreach loop with a lazy pipeline. For example, transform and filter an array of user IDs:

    use Iter\Iter;
    
    $userIds = [1, 2, 3, 4, 5];
    $activeUsers = Iter::from($userIds)
        ->filter(fn($id) => $id % 2 === 0) // Keep even IDs
        ->map(fn($id) => "user_$id")      // Prefix with "user_"
        ->toArray();                      // Materialize to array
    // Result: ["user_2", "user_4"]
    
  3. Key Entry Points:

    • Iter::from($iterable): Wrap any iterable (array, generator, Traversable).
    • Chain methods like map(), filter(), reduce(), chunk(), etc.
    • Materialize results with toArray(), toGenerator(), or iterate directly.
  4. Where to Look First:

    • API Reference (hypothetical link).
    • Focus on core methods: map, filter, reduce, flatMap, take, skip, chunk.

Implementation Patterns

Workflows

  1. Data Transformation Pipelines: Use map/flatMap to transform data in a declarative way. Example: Flatten nested arrays and filter:

    $nestedData = [[1, 2], [3, [4, 5]]];
    $flattened = Iter::from($nestedData)
        ->flatMap(fn($item) => is_array($item) ? $item : [$item])
        ->filter(fn($item) => $item > 2)
        ->toArray();
    // Result: [3, 4, 5]
    
  2. Lazy Evaluation: Avoid loading all data into memory upfront. Example: Process large files line-by-line:

    $lines = Iter::from($fileHandle)
        ->map('trim')
        ->filter(fn($line) => !empty($line))
        ->take(100); // Only process first 100 lines
    
  3. Integration with Laravel:

    • Collections: Convert Laravel Collections to Iter for custom logic:
      $users = User::all();
      $iter = Iter::from($users->toArray())
          ->filter(fn($user) => $user->is_active)
          ->map(fn($user) => $user->name);
      
    • Query Builders: Use chunk() to paginate results without cursor():
      $chunked = Iter::from($query->get())
          ->chunk(20)
          ->map(fn($chunk) => $chunk->toBase());
      
  4. Testing: Mock iterables in tests by returning Iter objects with predefined sequences:

    $mockIter = Iter::from([1, 2, 3])
        ->map(fn($i) => "item_$i");
    $this->assertEquals(["item_1", "item_2"], $mockIter->take(2)->toArray());
    

Integration Tips

  • Type Safety: Use Iter::from() to normalize mixed iterables (e.g., arrays from APIs vs. generators from DB).
  • Performance: Prefer toGenerator() over toArray() for large datasets to avoid memory spikes.
  • Error Handling: Wrap Iter in try-catch for external iterables (e.g., file handles) that might throw exceptions.
  • Laravel Service Providers: Bind Iter to the container for dependency injection:
    $this->app->bind(Iter::class, fn() => new Iter());
    

Gotchas and Tips

Pitfalls

  1. Immutable Iterables:

    • Methods like map() return new Iter objects; they don’t modify the original iterable.
    • Avoid chaining methods on the same object if you need to reuse the original data.
  2. Generator Exhaustion:

    • Generators can only be iterated once. If you need to reuse a generator, materialize it first:
      $gen = (fn() => yield 1, yield 2)();
      $iter = Iter::from($gen)->toArray(); // Materialize
      
  3. Lazy Evaluation Quirks:

    • Chained methods (e.g., filter()->map()) are lazy until materialized. Debugging intermediate steps requires explicit calls like toArray():
      $iter = Iter::from([1, 2, 3])->filter(fn($i) => $i > 1);
      // $iter still contains [1, 2, 3] until materialized!
      
  4. Edge Cases with null or Non-Iterables:

    • Iter::from(null) throws an exception. Use empty() checks or Iter::empty() for safe defaults:
      $iter = $data ? Iter::from($data) : Iter::empty();
      

Debugging

  • Inspect Iterables: Use Iter::from($iterable)->toArray() to debug intermediate states.
  • Short-Circuiting: Methods like take(1) or first() can help isolate issues in large pipelines.
  • Memory Leaks: Monitor memory usage with memory_get_usage() when working with large toArray() calls.

Tips

  1. Custom Iterables: Implement IteratorAggregate or Generator and pass to Iter::from() for seamless integration:

    class MyIterator implements IteratorAggregate {
        public function getIterator() { /* ... */ }
    }
    $iter = Iter::from(new MyIterator());
    
  2. Extension Points:

    • Create custom methods by composing existing ones:
      $iter->customMethod(fn($iter) => $iter->filter(...)->map(...));
      
    • Extend the Iter class for domain-specific logic (e.g., UserIter with activeOnly()).
  3. Performance Tuning:

    • For CPU-heavy transformations, use chunk() to parallelize work:
      $iter->chunk(100)->map(fn($chunk) => parallelProcess($chunk));
      
    • Avoid reduce() on large datasets; use fold() for incremental processing.
  4. Laravel-Specific:

    • Combine with Collection methods for hybrid pipelines:
      $result = Iter::from($collection->toArray())
          ->map(fn($item) => $collection->firstWhere('id', $item['id']))
          ->filter();
      
    • Use Iter in Eloquent relationships to transform related data:
      $user->posts()->get()->map(fn($post) => $post->title);
      // Replace with:
      Iter::from($user->posts)->map(fn($post) => $post->title);
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4