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+, supporting serializable containers, constructor and setter injection, interface/trait awareness, and configuration inheritance. Lightweight, standards-friendly, and flexible for complex apps.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install the package via Composer: composer require aura/di. Requires PHP 8.0+.
  2. Instantiate a ContainerBuilder, then build your container with configuration classes (or use newInstance() for quick setup).
  3. Define services using $di->set() and $di->lazyNew() before locking the container — prefer lazy construction during configuration.
  4. First real use case: Inject a simple service with constructor arguments:
    $di->set('db', $di->lazyNew(Database::class, [
        'dsn' => 'mysql:host=localhost;dbname=test',
        'user' => 'root',
        'pass' => '',
    ]));
    $db = $di->get('db'); // Returns same instance on subsequent calls
    
  5. Locking happens automatically on first get()/newInstance(), so organize all config upfront.

Implementation Patterns

  • Use ContainerBuilder + Config Classes: Create one or more classes implementing ContainerConfig (or extending AbstractConfig) to centralize service definitions and param overrides. Example:
    class AppConfig extends AbstractConfig {
        public function define() {
            $this->set('logger', $this->lazyNew(Logger::class));
        }
        public function modify() {
            $logger = $this->get('logger');
            $logger->setLevel('debug');
        }
    }
    $di = $builder->newConfiguredInstance([AppConfig::class]);
    
  • Leverage Attributes (PHP 8+): Annotate classes with #[Inject] for constructor/setter injection:
    class Service {
        #[Inject]
        public function setDb(Database $db) { ... }
    }
    
    Enable via ContainerBuilder::useAttributes(true) — avoids verbose param definitions.
  • Compile for Performance: Use newCompiledInstance() with ClassScannerConfig after scanning your codebase (vendor/bin/auradi scan). Serialize the compiled container to OPcache or file — ideal for production.
  • Contextual Injection: For nested dependencies needing different values in different contexts, use lazyNew()->withContext(Blueprint::class, [...]) instead of repeating full trees — keeps config DRY.
  • Auto-resolution with Typehints: Enable $di->autoResolve() (or rely on default) to resolve missing params via type-hinted constructors — but prefer explicit config for clarity and control.

Gotchas and Tips

  • Container locking is strict: Once you call get() or newInstance(), any further set(), params[] modification, or lazySet() throws an exception. Always configure fully before resolving.
  • newInstance() locks the container even inside config classes — use lazyNew() during definition, newInstance() only when you need an immediate, non-shared instance.
  • Use params arrays, not direct new calls, during config:
    // Good
    $di->params[SomeService::class]['dependency'] = $di->lazyNew(Dep::class);
    // ❌ Avoid (locks too early)
    $di->set('someService', new SomeService(new Dep()));
    
  • Memory & serialization: The container is serializable and meant to be compiled/cached. Don’t forget to warm the cache on deploy — cold-start containers (no cache) suffer performance penalties.
  • Trait/interface inheritance: params and setters from traits and interfaces are inherited automatically — useful for cross-cutting concerns (e.g., LoggerAwareInterface).
  • Debugging tip: Use Container::getServiceDefinition($name) to inspect how a service was defined — invaluable when troubleshooting injection mismatches.
  • Contextual Injection pitfalls: withContext() works only with lazyNew(), not newInstance(). For production, ensure context paths are shallow — deeply nested context trees can obscure logic.
  • Avoid service-locator anti-pattern: This container is for DI only. Calling get() throughout app code (instead of injecting the container into a few well-defined factories/bootstrap services) is discouraged.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport