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

Di Laravel Package

aura/di

Aura.Di is a PSR-11 dependency injection container for PHP 8+ with constructor and setter injection, interface and trait awareness, configurable wiring with inheritance, and support for serialization. Installable via Composer and fully documented.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require aura/di
    
  2. Basic Container Initialization:

    use Aura\Di\Container;
    use Aura\Di\ContainerBuilder;
    
    $builder = new ContainerBuilder();
    $container = $builder->newInstance();
    
  3. First Use Case: Manual Service Registration

    $container->set('serviceName', function ($di) {
        return new MyService($di->get('dependency'));
    });
    
  4. First Use Case: Attribute-Based Configuration (PHP 8.0+)

    use Aura\Di\Inject;
    
    class MyService {
        public function __construct(
            #[Inject] private MyDependency $dependency
        ) {}
    }
    
    // Configure scanner (see Implementation Patterns)
    

Where to Look First

  • Documentation (especially index.md and migrating.md for 5.x changes).
  • src/ for core classes (Container, ContainerBuilder, Inject attribute).
  • tests/ for usage examples and edge cases.

Implementation Patterns

Core Workflows

1. Attribute-Based Dependency Injection (Recommended for Laravel)

  • Annotations: Use PHP 8.0+ attributes (#[Inject], #[Service], #[Value]).
    use Aura\Di\Inject;
    
    class UserRepository {
        public function __construct(
            #[Inject] private DatabaseConnection $db,
            #[Inject] private LoggerInterface $logger
        ) {}
    }
    
  • Scanner Setup:
    use Aura\Di\Scanner\Scanner;
    use Aura\Di\Scanner\ClassScannerConfig;
    
    $scanner = new Scanner();
    $scanner->findClassesIn(__DIR__.'/App/Services');
    $scanner->scan($container);
    

2. Config Class Pattern (Legacy/Laravel Integration)

  • Define a config class to centralize DI rules:
    use Aura\Di\ContainerConfig;
    
    class AppConfig implements ContainerConfig {
        public function define(Aura\Di\Container $di): void {
            $di->params['UserRepository'][0] = $di->lazyNew('DatabaseConnection');
            $di->params['UserRepository'][1] = $di->lazyNew('Logger');
        }
    }
    
  • Build the container:
    $builder = new ContainerBuilder();
    $container = $builder->newInstance([AppConfig::class]);
    

3. Lazy Loading for Performance

  • Defer instantiation until first use:
    $container->lazyNew('ExpensiveService'); // Returns a LazyInterface
    $service = $container->get('ExpensiveService'); // Instantiates on demand
    
  • Contextual Parameters:
    $di->params['UserService']['locale'] = $di->lazyGet('Request')->lazyCall('getLocale');
    

4. Integration with Laravel Service Providers

  • Bind Aura.Di container to Laravel’s container:
    use Illuminate\Support\ServiceProvider;
    
    class AuraDiServiceProvider extends ServiceProvider {
        public function register() {
            $this->app->singleton('aura.di', function () {
                $builder = new ContainerBuilder();
                return $builder->newInstance([AppConfig::class]);
            });
        }
    }
    
  • Resolve services via Laravel’s container:
    $this->app->make('aura.di')->get('UserRepository');
    

5. Compiled Blueprints (Optimization)

  • Pre-compile configurations for runtime efficiency:
    use Aura\Di\Scanner\Compiler;
    
    $compiler = new Compiler();
    $compiler->compile($container, __DIR__.'/var/cache');
    
  • Load compiled blueprints:
    $container = ContainerBuilder::fromFile(__DIR__.'/var/cache/compiled.php');
    

Laravel-Specific Patterns

1. Replacing Laravel’s Container

  • Override Laravel’s container with Aura.Di in AppServiceProvider:
    public function boot() {
        $this->app->singleton('container', function () {
            $builder = new ContainerBuilder();
            return $builder->newInstance([AppConfig::class]);
        });
    }
    
  • Caveat: Requires careful handling of Laravel’s built-in bindings (e.g., Illuminate\Contracts\Container).

2. Hybrid Approach (Laravel + Aura.Di)

  • Use Aura.Di for domain-specific services while keeping Laravel’s container for framework services:
    $auraDi = $this->app->make('aura.di');
    $userRepo = $auraDi->get('UserRepository');
    

3. Testing with Aura.Di

  • Replace Laravel’s container in tests:
    use Aura\Di\Container;
    use Orchestra\Testbench\OverrideBindings;
    
    public function setUp(): void {
        parent::setUp();
        $this->app->instance('container', new Container());
    }
    

4. Serialization for Caching

  • Cache container configurations:
    $serialized = serialize($container);
    file_put_contents('cache/container.ser', $serialized);
    
    // Later...
    $container = unserialize(file_get_contents('cache/container.ser'));
    

Gotchas and Tips

Pitfalls

1. Auto-Resolution Quirks

  • Issue: Aura.Di auto-resolves type-hinted dependencies by default. This can lead to:
    • Circular dependencies (throws Aura\Di\Exception\CircularReference).
    • Unexpected instantiation of services not explicitly configured.
  • Fix: Disable auto-resolution for specific services:
    $container->setAutoResolve('MyService', false);
    
  • Laravel Tip: Disable globally in AppConfig:
    $di->setAutoResolve(false);
    

2. Attribute Scanner Limitations

  • Issue: The scanner may miss classes if:
    • They are in namespaces not scanned (e.g., vendor classes).
    • They use attributes from non-installed packages.
  • Fix: Explicitly include directories:
    $scanner->findClassesIn([
        __DIR__.'/App',
        __DIR__.'/Modules',
    ]);
    
  • Debugging: Check the class map:
    $scanner->getClassMap()->hasClass('My\Namespace\Class');
    

3. Compilation Pitfalls

  • Issue: Compiled blueprints may break if:
    • Class files are moved/deleted.
    • Attributes are added/removed without recompiling.
  • Fix: Clear cache on config changes:
    rm -rf var/cache && php artisan aura:compile
    
  • Laravel Integration: Add a custom Artisan command:
    use Aura\Di\Scanner\Compiler;
    use Illuminate\Console\Command;
    
    class CompileAuraDi extends Command {
        protected $signature = 'aura:compile';
        public function handle() {
            $compiler = new Compiler();
            $compiler->compile($this->app->make('aura.di'), storage_path('framework/cache'));
        }
    }
    

4. PHP 8.0+ Attribute Targets

  • Issue: Attributes like #[Service] must target TARGET_PROPERTY for constructor promotion:
    #[Service(target: Attribute::TARGET_PROPERTY)]
    public function __construct(private Database $db) {}
    
  • Fix: Ensure attributes are correctly annotated in your IDE (e.g., PHPStorm).

5. Lazy Loading Gotchas

  • Issue: Lazy services may not resolve as expected if:
    • Dependencies are not registered.
    • Circular lazy references exist.
  • Debugging: Use lazyLazy() for debugging:
    $container->lazyLazy('MyService')->__invoke(); // Force resolution
    

Debugging Tips

1. Enable Verbose Logging

  • Configure the scanner to log scanned classes:
    $scanner->setLogger(new \Monolog\Logger('scanner', [
        new \Monolog\Handler\StreamHandler(__DIR__.'/scanner.log', \Monolog\Logger::DEBUG),
    ]));
    

2. Inspect the Container State

  • Dump all registered services:
    print_r($container->getParams());
    
  • Check if a service exists:
    $container->has('MyService'); // Returns bool
    

3. Handle Reflection Errors

  • Wrap instantiation in try-catch:
    try {
        $service = $container->get('MyService');
    } catch (\ReflectionException $e) {
        Log::
    
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata