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

Object Models Laravel Package

coder-at-heart/object-models

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require coder-at-heart/object-models
    

    Register the service provider in config/app.php under providers:

    CoderAtHeart\ObjectModels\ObjectModelsServiceProvider::class,
    
  2. Basic Usage Define a model class extending CoderAtHeart\ObjectModels\ObjectModel:

    use CoderAtHeart\ObjectModels\ObjectModel;
    
    class UserModel extends ObjectModel
    {
        protected $schema = [
            'id' => 'integer',
            'name' => 'string',
            'email' => 'string',
            'is_active' => 'boolean',
        ];
    }
    
  3. First Use Case: Parsing JSON

    $json = '{"id": 1, "name": "John", "email": "john@example.com"}';
    $user = UserModel::fromJson($json);
    echo $user->name; // Outputs: John
    
  4. Key Files to Explore

    • src/ObjectModel.php: Core class with schema validation, casting, and control logic.
    • src/ObjectModelsServiceProvider.php: Service provider for package registration.
    • tests/: Unit tests demonstrating usage patterns.

Implementation Patterns

Schema Definition

  • Type-Safe Models: Define strict schemas to enforce data types (e.g., integer, string, boolean, array, object).
    protected $schema = [
        'posts' => 'array',
        'metadata' => 'object',
    ];
    
  • Nested Objects: Use dot notation for nested schemas:
    protected $schema = [
        'user.address.city' => 'string',
        'user.address.zip' => 'integer',
    ];
    

Data Transformation

  • Casting: Automatically cast data to defined types:
    $data = ['id' => '123', 'is_active' => 'yes'];
    $user = UserModel::fromArray($data);
    // $user->id is integer, $user->is_active is boolean
    
  • Default Values: Set defaults in schema:
    protected $schema = [
        'is_active' => ['type' => 'boolean', 'default' => true],
    ];
    

Validation and Control

  • Validation Rules: Extend validation with custom rules:
    protected $rules = [
        'email' => 'required|email',
        'age' => 'integer|min:18',
    ];
    
  • Custom Logic: Override validate() or cast() methods for custom logic:
    protected function castIsActive($value)
    {
        return strtolower($value) === 'true';
    }
    

Integration with Laravel

  • Eloquent Models: Use alongside Eloquent for API responses:
    class User extends Model
    {
        public function toApiResponse()
        {
            return UserModel::fromArray($this->toArray());
        }
    }
    
  • Request Validation: Validate incoming requests:
    $requestData = $request->all();
    $userModel = UserModel::fromArray($requestData);
    if ($userModel->isValid()) {
        // Proceed with valid data
    }
    

Collections

  • Model Collections: Convert arrays of JSON/objects to collections:
    $jsonArray = '[{"id": 1}, {"id": 2}]';
    $users = UserModel::collectionFromJson($jsonArray);
    foreach ($users as $user) {
        echo $user->id;
    }
    

Gotchas and Tips

Pitfalls

  • Schema Mismatch Errors: Ensure JSON/array keys match schema keys exactly (case-sensitive).
    // Fails: 'Name' !== 'name'
    $data = ['Name' => 'John'];
    $user = UserModel::fromArray($data); // Throws exception
    
  • Circular References: Avoid circular references in nested objects/arrays (e.g., user.friends containing user).
  • Type Casting Overhead: Excessive casting (e.g., deeply nested objects) may impact performance. Benchmark for critical paths.

Debugging

  • Validation Errors: Check $model->errors() for validation failures:
    $user = UserModel::fromArray(['email' => 'invalid']);
    if ($user->hasErrors()) {
        dd($user->errors());
    }
    
  • Schema Debugging: Use dumpSchema() to inspect schema:
    $user = new UserModel();
    $user->dumpSchema(); // Outputs schema structure
    

Configuration Quirks

  • Global Defaults: Override global defaults in config/object-models.php (if provided in future updates).
  • Lazy Loading: Schema validation runs on fromArray()/fromJson(), not on instantiation. Initialize with empty data to defer validation:
    $user = new UserModel(['id' => null]); // No validation until data is set
    

Extension Points

  • Custom Casts: Extend CoderAtHeart\ObjectModels\Casters\CasterInterface for custom types:
    class DateCaster implements CasterInterface
    {
        public function cast($value, $type)
        {
            return \Carbon\Carbon::parse($value);
        }
    }
    
    Register in ObjectModel:
    protected $customCasters = [
        'date' => DateCaster::class,
    ];
    
  • Hooks: Override lifecycle methods:
    protected function beforeValidate()
    {
        // Pre-validation logic
    }
    
    protected function afterCast()
    {
        // Post-casting logic
    }
    

Performance Tips

  • Reuse Instances: Reuse ObjectModel instances for repeated operations:
    $user = new UserModel();
    foreach ($jsonArray as $data) {
        $user->fromArray($data);
        // Use $user->data
    }
    
  • Disable Validation: Temporarily disable validation for bulk operations:
    $user = new UserModel(['validate' => false]);
    $user->fromArray($data);
    
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.
croct/coding-standard
croct/plug-php
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php
trappistes/laravel-custom-fields
splash/sonata-admin
splash/metadata