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

Model Laravel Package

memio/model

Memio Model provides PHP objects to describe code structures (classes, interfaces, methods, properties, parameters, types and namespaces). Use it to build an in-memory representation of PHP code for analysis, tooling, or code generation workflows.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require memio/model
    

    Ensure memio/model is listed in composer.json under require.

  2. Basic Usage: Start by describing a simple model class:

    use Memio\Model\Describer;
    
    $describer = new Describer();
    $model = $describer->describe([
        'name' => 'User',
        'properties' => [
            'id' => ['type' => 'int', 'primary' => true],
            'name' => ['type' => 'string', 'maxLength' => 255],
            'email' => ['type' => 'string', 'unique' => true],
            'created_at' => ['type' => 'datetime'],
        ],
    ]);
    

    This generates a User model class dynamically with the specified properties.

  3. First Use Case: Use memio/model to scaffold a Laravel Eloquent model without writing boilerplate:

    $model = $describer->describe([...])->generate();
    $model->save(['name' => 'John Doe', 'email' => 'john@example.com']);
    

Where to Look First

  • Documentation: Check the Memio Model Docs (if available) for advanced features like relationships, events, or custom logic.
  • Examples: Browse the tests/ directory in the package for real-world usage patterns.
  • API: Focus on Describer, Generator, and Model classes in the Memio\Model namespace.

Implementation Patterns

Dynamic Model Generation

  1. Scaffolding Models: Use Describer to generate models from database schemas or API contracts:

    $schema = DB::select('SHOW COLUMNS FROM users');
    $describer->describeFromSchema($schema)->generate();
    
  2. Integration with Laravel: Override Laravel’s model generation by hooking into booted events:

    Model::booted(function () {
        $describer = new Describer();
        $describer->describe([...])->generate();
    });
    

Relationships and Events

  1. Define Relationships:

    $describer->describe([
        'name' => 'Post',
        'properties' => [...],
        'relationships' => [
            'author' => ['type' => 'belongsTo', 'model' => 'User'],
            'comments' => ['type' => 'hasMany', 'model' => 'Comment'],
        ],
    ]);
    
  2. Add Events:

    $describer->describe([
        'name' => 'Order',
        'events' => [
            'creating' => 'validateStock',
            'saved' => 'sendNotification',
        ],
    ]);
    

API Contracts

Use memio/model to validate incoming requests:

use Memio\Model\Validator;

$validator = new Validator();
$input = $request->all();
$errors = $validator->validate($input, $describer->describe([...]));

Workflows

  1. Database-First Development:
    • Extract schema from DB → Generate models → Use in Laravel.
  2. API-First Development:
    • Define OpenAPI/Swagger contracts → Generate models → Validate requests.
  3. Legacy Migration:
    • Describe existing models → Add missing methods → Gradually replace old code.

Gotchas and Tips

Pitfalls

  1. Caching Generated Models: Memio generates classes at runtime. Cache the output to avoid regeneration:

    $generatedClass = $describer->describe([...])->generate();
    file_put_contents(app_path("Models/Generated/{$generatedClass->getName()}.php"), $generatedClass->getCode());
    
  2. Namespace Conflicts: Ensure generated model namespaces match your Laravel app’s structure:

    $describer->setNamespace('App\Models');
    
  3. Type System Limitations: Memio’s type system is PHP 8.0+ focused. For older PHP, use string as a fallback.

  4. Database Sync Issues: If the DB schema changes, regenerate models to avoid ColumnNotFoundException.

Debugging

  • Verify Descriptions: Use dd($describer->describe([...])->getModel()) to inspect the generated structure.
  • Check Generated Code:
    $code = $describer->describe([...])->generate()->getCode();
    file_put_contents('debug_model.php', $code);
    
  • Enable Strict Mode:
    $describer->setStrict(true); // Throws exceptions for invalid descriptions.
    

Extension Points

  1. Custom Generators: Extend Memio\Model\Generator to add Laravel-specific traits:

    class LaravelGenerator extends Generator {
        public function generate(): Model {
            $model = parent::generate();
            $model->addTrait('Illuminate\Database\Eloquent\Concerns\HasUuids::class');
            return $model;
        }
    }
    
  2. Plugin System: Use Describer::addPlugin() to inject custom logic (e.g., soft deletes):

    $describer->addPlugin(function ($description) {
        $description['properties']['deleted_at'] = ['type' => 'datetime', 'nullable' => true];
    });
    
  3. Event Hooks: Override Model::fireModelEvent() to integrate with Laravel’s event system:

    $model->on('saving', function ($model) {
        $model->updated_at = now();
    });
    

Config Quirks

  • Autoloading: Ensure generated models are autoloaded by adding them to composer.json:
    "autoload": {
        "psr-4": {
            "App\\Models\\Generated\\": "app/Models/Generated/"
        }
    }
    
  • Performance: Disable regeneration in production by checking the environment:
    if (app()->environment('production')) {
        $describer->disableRegeneration();
    }
    
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