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

Php Data Laravel Package

event-engine/php-data

Immutable PHP value objects and data containers for event-driven apps. Provides typed properties, casting, validation, and convenient hydration from arrays/JSON, plus serialization back to payloads—useful for messages, commands, events, and read models in Event Engine setups.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require event-engine/php-data:^2.1
    

    Add to composer.json under require if not auto-loaded.

  2. First Use Case Define an immutable event object with JSON serialization support:

    use EventEngine\Data\Immutable;
    
    class UserRegisteredEvent extends Immutable
    {
        public function __construct(
            public string $userId,
            public string $email,
            public array $metadata = []
        ) {}
    }
    

    Usage:

    $event = new UserRegisteredEvent('123', 'user@example.com', ['source' => 'web']);
    // $event->userId = '456'; // Throws Error (immutable)
    
    // Native JSON serialization now works
    $json = json_encode($event);
    $decoded = json_decode($json, true);
    
  3. Key Files

    • src/Immutable.php (core class with JSON support)
    • src/ImmutableCollection.php (for arrays)
    • tests/ (usage examples with serialization tests)

Implementation Patterns

Core Workflows

  1. Event Modeling with JSON Support

    // Domain events as immutable objects with native JSON serialization
    class OrderPlacedEvent extends Immutable {
        public function __construct(
            public string $orderId,
            public float $total,
            public array $items
        ) {}
    }
    
    // Direct JSON conversion
    $json = json_encode(new OrderPlacedEvent('123', 99.99, []));
    $event = json_decode($json, false, 512, JSON_THROW_ON_ERROR);
    
  2. Data Validation Leverage constructor type hints + runtime checks:

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new \InvalidArgumentException("Invalid email");
    }
    
  3. Collection Handling

    use EventEngine\Data\ImmutableCollection;
    
    $events = new ImmutableCollection([
        new UserRegisteredEvent(...),
        new UserRegisteredEvent(...),
    ]);
    
    // Collections also support JSON serialization
    $json = json_encode($events);
    
  4. API Responses Return immutable objects directly from controllers:

    return response()->json(new UserRegisteredEvent('123', 'user@example.com'));
    

Integration Tips

  • Laravel Events: Use as event payloads with automatic JSON conversion:
    event(new OrderPlacedEvent($orderId, $total, $items));
    // Will serialize automatically when needed
    
  • API Requests: Deserialize JSON payloads directly:
    $requestData = json_decode($request->getContent(), false, 512, JSON_THROW_ON_ERROR);
    $event = new UserRegisteredEvent(...array_values($requestData));
    
  • Testing: Mock immutable objects with JSON assertions:
    $event = new UserRegisteredEvent(...);
    $this->assertEquals(json_encode($event), '{"userId":"123","email":"user@example.com"}');
    

Gotchas and Tips

Pitfalls

  1. Deep Immutability

    • Nested objects/arrays must still be immutable:
      // ❌ Breaks immutability
      $event = new UserRegisteredEvent('123', 'user@example.com', ['tags' => []]);
      $event->metadata['tags'][] = 'premium'; // Mutates!
      
      // ✅ Solution: Use ImmutableCollection for arrays
      
  2. JSON Serialization Edge Cases

    • Custom objects in properties require __serialize()/__unserialize():
      class CustomEvent extends Immutable {
          public function __construct(public DateTime $createdAt) {}
      
          // Required for full JSON support
          public function jsonSerialize(): array {
              return ['created_at' => $this->createdAt->format('c')];
          }
      }
      
  3. Performance

    • Avoid heavy computations in constructors (immutability forces upfront validation).
    • JSON serialization adds minimal overhead (~5-10% for complex objects).

Debugging

  • Property Access Errors: Use get_object_vars() to inspect properties:
    print_r(get_object_vars($event));
    
  • Serialization Failures: Check for non-JSON-serializable properties:
    if (!json_encode($event)) {
        throw new \RuntimeException("Serialization failed");
    }
    

Extension Points

  1. Custom JSON Handling Implement JsonSerializable interface for complex types:

    class ComplexEvent extends Immutable implements JsonSerializable {
        public function jsonSerialize(): array {
            return [
                'id' => $this->id,
                'metadata' => $this->metadata->toArray()
            ];
        }
    }
    
  2. Magic Methods Add __toString() or __invoke() for domain-specific behavior:

    public function __toString(): string {
        return "Order #{$this->orderId} placed for {$this->total}";
    }
    
  3. Laravel Integration Use HasFactory with immutable objects:

    class UserRegisteredEventFactory {
        public function create(): UserRegisteredEvent {
            return new UserRegisteredEvent(
                Str::uuid()->toString(),
                'user@example.com'
            );
        }
    }
    
    // JSON serialization works with factories
    $json = json_encode((new UserRegisteredEventFactory())->create());
    
  4. Collection JSON Support

    $collection = new ImmutableCollection([$event1, $event2]);
    $json = json_encode($collection); // Works natively
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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