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

Utilities Bags Laravel Package

myerscode/utilities-bags

Immutable “Bag” utilities for fluent manipulation of collection/array data in PHP. Provides a helper class with chainable methods for reading, transforming, and managing data safely without mutation; includes usage and method docs, plus tests and coverage.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require myerscode/utilities-bags
    
  2. Basic Usage:

    use Myerscode\Utilities\Bag;
    
    // From array
    $bag = Bag::from([1, 2, 3]);
    
    // From Laravel Collection
    $bag = collect([1, 2, 3])->toBag();
    
    // Global helper (added in 2025.1.0)
    $bag = bag([1, 2, 3]);
    
  3. First Use Case: Filter and transform an array immutably:

    $result = Bag::from([1, 2, 3, 4, 5])
        ->filter(fn($item) => $item % 2 === 0)
        ->map(fn($item) => $item * 2)
        ->toArray(); // [4, 8]
    

Where to Look First

  • Usage Guide for core patterns.
  • Methods Documentation for API reference.
  • Laravel Integration: Check Illuminate\Support\Collection compatibility (e.g., toBag() method).

Implementation Patterns

Core Workflows

1. Immutable Data Pipelines

// Process API response immutably
$response = Bag::from($apiData)
    ->pluck('user.id')
    ->filter(fn($id) => $id > 100)
    ->groupBy(fn($id) => (int)($id / 10))
    ->toArray();

2. Laravel Integration

// Replace collect() for immutable ops
$users = User::where('active', true)->get()->toBag()
    ->map(fn($user) => $user->only(['id', 'name']))
    ->toArray();

// Chain with Eloquent
$stats = Order::query()
    ->whereYear('created_at', now()->year)
    ->get()
    ->toBag()
    ->sum('amount')
    ->toFloat();

3. Domain-Specific Bags

// Encapsulate business logic
class OrderBag extends Bag {
    public function applyDiscount(float $discount): static {
        return $this->map(fn($order) => [
            ...$order,
            'discounted_price' => $order['price'] * (1 - $discount),
        ]);
    }
}

// Usage
$orders = OrderBag::from($orderData)
    ->applyDiscount(0.1)
    ->filter(fn($order) => $order['discounted_price'] > 100);

4. Testing Utilities

// Mock immutable data for tests
$testData = Bag::make()
    ->merge(['user' => ['id' => 1, 'name' => 'Test']])
    ->merge(['roles' => ['admin']])
    ->toArray();

$this->assertEquals(['admin'], $testData['roles']);

Integration Tips

  • Service Providers: Register a global helper in AppServiceProvider:
    Bag::macro('customMethod', function() {
        return $this->filter(fn($item) => /* ... */);
    });
    
  • API Responses: Use toJson() for direct HTTP responses:
    return response()->json(
        Bag::from($data)->only(['id', 'name'])->toJson()
    );
    
  • CLI Scripts: Process files/arrays immutably:
    $lines = Bag::from(file($filePath))
        ->filter(fn($line) => str_contains($line, 'search'))
        ->map('trim')
        ->toArray();
    

Gotchas and Tips

Pitfalls

  1. Immutability Overhead:

    • Every method returns a new Bag instance. Avoid chaining excessively in performance-critical paths.
    • Workaround: Use toArray() early to break immutability if needed.
  2. Laravel Collection Confusion:

    • toBag() converts to Bag, but Bag methods do not mirror Collection (e.g., no first() until 2026.0.0).
    • Tip: Prefer Bag for immutable ops; use collect() for Laravel-specific features.
  3. PHP 8.5 Dependency:

    • Features like named arguments or readonly properties are leveraged. Downgrading may break functionality.
  4. Edge Cases:

    • isEmpty()/isNotEmpty() return booleans, not Bag instances (unlike other methods).
    • reduce() requires a non-null initial value (unlike JS/PHP’s array_reduce).

Debugging

  • Method Chaining Issues:
    • Verify each method returns static (self). Example:
      // Debug: Check return type
      dd(get_class($bag->filter(...))); // Should be Myerscode\Utilities\Bag
      
  • Performance:
    • Profile with Xdebug if chaining >5 methods. Consider intermediate toArray() calls.

Extension Points

  1. Custom Methods:
    Bag::macro('avg', function() {
        return $this->sum() / $this->count();
    });
    
  2. Override Defaults:
    Bag::setDefaultDriver('array'); // Force array-based storage
    
  3. Global Helpers:
    • Extend the bag() helper in composer.json autoload:
      "extra": {
          "laravel": {
              "providers": ["Myerscode\\Utilities\\BagServiceProvider"]
          }
      }
      

Tips

  • Use pipe() for Complex Logic:
    $result = Bag::from($data)
        ->pipe(fn($bag) => $bag->filter(...)->map(...))
        ->pipe(fn($bag) => $bag->groupBy(...));
    
  • Leverage only()/except() for API Responses:
    return $this->bag($user)->only(['id', 'name', 'email'])->toJson();
    
  • Combine with Laravel:
    • Use Bag for request data:
      $validated = Bag::from($request->all())
          ->only(['email', 'name'])
          ->toArray();
      
    • Use collect() for Eloquent relationships:
      $user->posts->toBag()->pluck('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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor