Weave 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

Commons Laravel Package

adimeo-data-suite/commons

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require adimeo-data-suite/commons
    
    • No additional configuration is required for basic usage.
  2. Core Classes

    • The package provides a DataSuite\Commons\DataObject base class for immutable data structures.
    • Key features:
      • Type-safe property access via __get()/__set() magic.
      • Built-in serialization (JSON, array) via toArray()/toJson().
      • Immutable by default (modify via with() method).
  3. First Use Case

    use DataSuite\Commons\DataObject;
    
    class User extends DataObject
    {
        protected $name;
        protected $email;
    }
    
    $user = new User(['name' => 'John', 'email' => '[email protected]']);
    echo $user->name; // "John"
    echo $user->toJson(); // '{"name":"John","email":"[email protected]"}'
    

Implementation Patterns

1. Data Modeling

  • Immutable Data Objects Use DataObject for domain models where state should not change after creation.

    $user = new User(['id' => 1]);
    $updated = $user->with(['name' => 'Alice']); // Returns new instance
    
  • Nested Data Structures Support nested DataObject instances for complex hierarchies.

    class Address extends DataObject { /* ... */ }
    class User extends DataObject {
        protected $address;
    }
    $user = new User(['address' => new Address(['city' => 'Paris'])]);
    

2. Validation & Transformation

  • Predefined Validation Extend DataObject and override validate() for custom rules.

    protected function validate(array $data): void {
        if (empty($data['email'])) {
            throw new \InvalidArgumentException('Email is required.');
        }
    }
    
  • Mass Assignment Protection Use $fillable to whitelist allowed properties.

    protected $fillable = ['name', 'email']; // Only these can be set
    

3. Integration with Laravel

  • Eloquent Models Use DataObject for DTOs alongside Eloquent.

    $user = User::find(1);
    $dto = new UserDto($user->toArray());
    
  • API Responses Convert Eloquent collections to DataObject arrays for consistent API output.

    return response()->json(array_map(fn ($user) => new UserDto($user), User::all()));
    
  • Form Requests Validate incoming requests and map to DataObject.

    $validated = $request->validate([...]);
    $user = new User($validated);
    

4. Serialization & Hydration

  • JSON/Array Conversion Leverage toArray()/toJson() for seamless API/DB interactions.

    $json = $user->toJson();
    $array = json_decode($json, true);
    
  • Hydration from External Sources

    $data = json_decode(file_get_contents('data.json'), true);
    $user = new User($data);
    

Gotchas and Tips

Pitfalls

  1. Immutability Overhead

    • Every "update" via with() creates a new instance. Use sparingly for performance-critical paths.
    • Workaround: Use mutable properties if needed (but lose immutability guarantees).
  2. Magic Methods Quirks

    • __get()/__set() bypass type safety. Ensure properties are properly typed in child classes.
    • Tip: Add PHPDoc @property annotations for IDE support.
      /** @property string $name */
      
  3. Validation Timing

    • Validation runs on instantiation. If data is incomplete, throw early.
    • Tip: Use try-catch for graceful handling:
      try {
          $user = new User($request->all());
      } catch (\InvalidArgumentException $e) {
          return response()->json(['error' => $e->getMessage()], 400);
      }
      
  4. Circular References

    • Nested DataObjects with circular references (e.g., User->address->user) will cause infinite recursion in toArray().
    • Fix: Implement __toArray() in child classes to handle cycles:
      public function __toArray(): array {
          return [
              'city' => $this->city,
              // Exclude 'user' to break the cycle
          ];
      }
      

Debugging Tips

  • Enable Strict Typing Add declare(strict_types=1); to child classes to catch type mismatches early.

  • Log DataObject Contents Override __toString() for debugging:

    public function __toString(): string {
        return $this->toJson();
    }
    

Extension Points

  1. Custom Serialization Override toArray() for tailored output:

    public function toArray(): array {
        return ['full_name' => "{$this->first} {$this->last}"];
    }
    
  2. Dynamic Properties Use offsetGet()/offsetSet() for dynamic keys (less type-safe):

    public function offsetGet($offset) { /* ... */ }
    public function offsetSet($offset, $value) { /* ... */ }
    
  3. Event Dispatching Trigger events on instantiation/modification:

    public function __construct(array $data) {
        parent::__construct($data);
        event(new UserCreated($this));
    }
    

Performance Considerations

  • Avoid Deep Cloning with() creates a shallow copy by default. For large objects, optimize by:

    $updated = clone $user;
    $updated->name = 'Alice'; // Manual mutation (not immutable)
    
  • Batch Processing Use array_map() with DataObject::fromArray() for bulk conversion:

    $users = array_map([User::class, 'fromArray'], $rawData);
    
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.
hsluv/hsluv
seampact/codegen
seampact/hooks
seampact/ir
mehedimi/laravel-amp-mail
happones/laravel-vue-i18n-generator
jwerd/inertia-table
siberfx/flysystem-wasabi
hollyit/token-replace
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support