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

Bag Laravel Package

avris/bag

avris/bag is a small Laravel/PHP utility package providing a “bag” style container for working with grouped values and simple data access. Handy for passing around structured payloads, storing arbitrary attributes, and keeping collections of data lightweight.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation Add the package via Composer:

    composer require avris/bag
    

    No additional configuration is required—it’s a drop-in replacement for PHP arrays with enhanced functionality.

  2. First Use Case Replace a standard PHP array with a Bag instance:

    use Avris\Bag\Bag;
    
    $bag = new Bag(['name' => 'John', 'age' => 30]);
    echo $bag->name; // Access properties directly
    echo $bag['age']; // Fallback to array syntax
    
  3. Where to Look First

    • Core Methods: Check Bag.php for magic methods (__get, __set, __isset, __unset).
    • Documentation: The package is minimal; refer to the GitLab repo for basic usage examples.
    • Laravel Integration: Works seamlessly with Laravel’s service container and Blade templates.

Implementation Patterns

Usage Patterns

  1. Property Access Over Arrays Prefer dot notation for readability:

    $bag = new Bag(['user' => ['name' => 'Alice']]);
    echo $bag->user->name; // 'Alice' (nested access)
    
  2. Fluent Method Chaining Use put() and merge() for dynamic data manipulation:

    $bag->put('status', 'active')->merge(['role' => 'admin']);
    
  3. Laravel-Specific Workflows

    • Service Container Binding:
      $this->app->bind(Bag::class, function () {
          return new Bag(request()->all());
      });
      
    • Blade Templates:
      @foreach($bag->items as $item)
          {{ $item->name }}
      @endforeach
      
  4. Data Validation Combine with Laravel’s Validator:

    $validator = Validator::make($bag->toArray(), [
        'name' => 'required|string',
        'age' => 'integer|min:18',
    ]);
    

Integration Tips

  • Replace Native Arrays: Use Bag in controllers, services, or DTOs to enforce structured access.
    public function store(Request $request) {
        $data = new Bag($request->validated());
        // ...
    }
    
  • API Responses: Convert Bag to JSON with json_encode($bag) (implements JsonSerializable).
  • Testing: Mock Bag in PHPUnit for predictable property access:
    $this->partialMock(Bag::class, ['__get']);
    

Gotchas and Tips

Pitfalls

  1. Nested Property Access Limits

    • Issue: Deeply nested properties (e.g., $bag->a->b->c) may fail if intermediate keys are missing.
    • Fix: Use data_get() or data_set() for safe access:
      $value = $bag->get('a.b.c', null);
      
  2. Type Juggling

    • Issue: Bag casts keys/values to strings (like arrays), which may cause unexpected behavior with objects.
    • Fix: Explicitly cast or use array_walk for type enforcement.
  3. Serialization Quirks

    • Issue: serialize()/unserialize() may not preserve object state.
    • Fix: Use toArray() + json_encode() for persistence.

Debugging

  • Check for Overrides: If $bag->method fails, verify no custom __get/__call conflicts exist.
  • Enable Strict Typing: Add declare(strict_types=1); to catch type-related issues early.

Extension Points

  1. Custom Magic Methods Extend Bag to add domain-specific methods:
    class UserBag extends Bag {
        public function isAdmin() {
            return $this->role === 'admin';
        }
    }
    
  2. Event Hooks Override __set to trigger events:
    protected function __set($key, $value) {
        event(new BagUpdated($this, $key, $value));
        parent::__set($key, $value);
    }
    
  3. Laravel Service Provider Bind a custom Bag class globally:
    $this->app->bind(Bag::class, function () {
        return new UserBag();
    });
    

Config Quirks

  • No Configuration File: The package is stateless; all behavior is code-driven.
  • Performance: Avoid overusing Bag for large datasets (memory overhead vs. native arrays).
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours