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

Bdf Instantiator Laravel Package

b2pweb/bdf-instantiator

b2pweb/bdf-instantiator is a small PHP utility for instantiating objects, useful in factories, DI containers, and testing. It focuses on creating class instances with minimal boilerplate, helping streamline object construction in Laravel and other PHP apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require b2pweb/bdf-instantiator
    

    Ensure b2pweb/bdf-instantiator is listed in composer.json under require.

  2. Service Provider Registration Add the service provider to config/app.php under providers:

    B2PWeb\BDFInstantiator\BDFInstantiatorServiceProvider::class,
    
  3. Publish Config (Optional) If customization is needed, publish the config:

    php artisan vendor:publish --provider="B2PWeb\BDFInstantiator\BDFInstantiatorServiceProvider" --tag="config"
    

    Config file: config/bdf-instantiator.php.

  4. First Use Case: Dynamic Model Instantiation Use the facade or service container to instantiate models dynamically:

    use B2PWeb\BDFInstantiator\Facades\BDFInstantiator;
    
    $model = BDFInstantiator::make('App\Models\User', ['name' => 'John']);
    

Implementation Patterns

Dynamic Model Creation

  • Facade Usage

    $user = BDFInstantiator::make('App\Models\User', ['email' => '[email protected]']);
    $user->save(); // Persist to DB
    
    • Ideal for factory-like model generation in tests, seeds, or bulk operations.
  • Service Container Binding Bind a custom instantiator for specific models:

    $this->app->bind('custom.instantiator', function ($app) {
        return new B2PWeb\BDFInstantiator\CustomInstantiator();
    });
    

Integration with Laravel Features

  • Eloquent Relationships Instantiate related models in a single call:

    $post = BDFInstantiator::make('App\Models\Post', [
        'title' => 'Test Post',
        'author' => BDFInstantiator::make('App\Models\User', ['name' => 'Author'])
    ]);
    
  • Events & Observers Trigger observers during instantiation:

    BDFInstantiator::make('App\Models\Order', [], [
        'observers' => ['App\Observers\OrderObserver']
    ]);
    
  • API Responses Useful for generating serializable model instances:

    $data = BDFInstantiator::make('App\Models\Product', ['price' => 99.99])->toArray();
    return response()->json($data);
    

Workflow: Bulk Data Generation

$users = collect(range(1, 10))->map(function ($i) {
    return BDFInstantiator::make('App\Models\User', [
        'name' => "User {$i}",
        'email' => "user{$i}@example.com"
    ]);
})->all();

// Save all at once
DB::transaction(function () use ($users) {
    foreach ($users as $user) {
        $user->save();
    }
});

Gotchas and Tips

Pitfalls

  1. Circular Dependencies Avoid instantiating models with recursive relationships (e.g., User has Post, Post has User). Workaround: Use partial data or lazy-load relationships.

  2. Observer Conflicts If multiple observers are registered, ensure they don’t interfere with instantiation logic. Debug: Temporarily disable observers to isolate issues:

    BDFInstantiator::make('App\Models\Order', [], ['observers' => []]);
    
  3. Config Overrides Published config (config/bdf-instantiator.php) may override default behavior. Tip: Check for default_attributes, casts, or observers in the config.

  4. Performance with Large Datasets Instantiating hundreds of models at once can be memory-intensive. Optimization: Use chunking or queue jobs:

    foreach (range(1, 1000) as $i) {
        BDFInstantiator::make('App\Models\Log')->dispatch();
    }
    

Debugging Tips

  • Log Instantiation Enable debug mode in config:

    'debug' => env('APP_DEBUG', false),
    

    Logs will appear in storage/logs/laravel.log.

  • Inspect Instantiated Models Use dd() to verify attributes:

    $model = BDFInstantiator::make('App\Models\Product');
    dd($model->getAttributes());
    
  • Custom Instantiator Classes Extend the base class for specialized logic:

    use B2PWeb\BDFInstantiator\Instantiator;
    
    class CustomInstantiator extends Instantiator {
        public function make($model, array $attributes = [], array $options = []) {
            // Add custom logic here
            return parent::make($model, $attributes, $options);
        }
    }
    

Extension Points

  1. Macros Add static methods to the facade:

    BDFInstantiator::macro('withSoftDeletes', function ($model, $attributes = []) {
        return $this->make($model, array_merge($attributes, [
            'deleted_at' => now()
        ]));
    });
    

    Usage:

    $deletedUser = BDFInstantiator::withSoftDeletes('App\Models\User');
    
  2. Middleware for Instantiation Apply middleware to instantiated models:

    BDFInstantiator::make('App\Models\Post', [], [
        'middleware' => ['App\Http\Middleware\LogActivity']
    ]);
    
  3. Event Listeners Listen for bdf.instantiator.created events:

    event(new \B2PWeb\BDFInstantiator\Events\ModelInstantiated($model));
    
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.
skyraptor/chatter
edlugz/sasapay
abbasudo/artisan-route
mirvan/ippanel
ignibyte/aic-framework
glavweb/data-schema-bundle
glavweb/datagrid-bundle
tacticmedia/scim-server
uni-method/frame
neika-ai/sdk
adachsoft/php-code-style
pharaonic/laravel-notification-dependencies
beautinow/translug
dev-brainiac/bot-cloaked
octoberrain/html
octoberrain/extension
octoberrain/exception
octoberrain/contracts
adachsoft/api-version-bundle
cgv/localized-resource