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

nette/di

Nette DI is a fast, configurable dependency injection container for PHP. Compile-time container generation boosts performance, while extensions, autowiring, and service definitions make complex apps easy to wire. Integrates smoothly with the Nette framework or standalone.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nette/di
    

    Add to your composer.json under autoload-dev for development:

    "autoload-dev": {
        "psr-4": {
            "App\\": "src/"
        }
    }
    
  2. Basic Container Initialization:

    use Nette\DI\ContainerLoader;
    use Nette\DI\Container;
    
    $loader = new ContainerLoader($tempDir, $mode);
    $container = $loader->load(function ($container) {
        // Define services here
        $container->addService('logger', new \Monolog\Logger('app'));
    });
    
  3. First Use Case: Define a service and inject it into a class:

    $container->addService('mailer', new \App\Mailer());
    $mailer = $container->getService('mailer');
    

Where to Look First

  • Documentation – Start with the "Getting Started" guide.
  • src/ – Core classes like Container, ContainerBuilder, and ServiceDefinition.
  • tests/ – Real-world usage examples and edge cases.
  • examples/ – Quick demos for autowiring, decorators, and extensions.

Implementation Patterns

Core Workflows

1. Autowiring

Leverage PHP type hints for automatic dependency resolution:

// In your config (Neon/YAML or PHP)
services:
    - App\Services\UserService
    - App\Services\LoggerService

// No manual binding needed; DI resolves dependencies via constructor/type hints.

2. Configuration-Driven Setup

Use Neon/YAML for declarative service definitions:

services:
    database:
        type: PDO
        arguments:
            - 'mysql:host=localhost;dbname=test'
            - 'user'
            - 'pass'

    repository:
        type: App\Repositories\UserRepository
        arguments:
            database: @database

3. Compiler Extensions

Modularize container setup with extensions:

use Nette\DI\CompilerExtension;

class MyExtension extends CompilerExtension {
    public function loadConfiguration() {
        $builder = $this->getContainerBuilder();
        $builder->addService('myService', new \App\MyService());
    }
}

Register in bootstrap.php:

$container->addExtension(new MyExtension());

4. Lazy Services

Delay initialization until first use (PHP 8.4+):

$container->addLazyService('expensiveService', function () {
    return new \App\ExpensiveService();
});

5. Decorators

Wrap services dynamically:

services:
    logger:
        type: App\Services\Logger
        decorate: true

    logger.decorator:
        type: App\Services\Decorators\LogDecorator
        arguments:
            original: @logger

Integration Tips

Laravel-Specific Adaptations

While nette/di isn’t Laravel-native, integrate it as a standalone container for:

  • Non-Laravel microservices in a monorepo.
  • Legacy codebases needing DI without Symfony’s overhead.
  • Testing: Use it to mock Laravel’s container in unit tests:
    $container = new Container();
    $container->addService('userRepository', $mockRepo);
    $this->app->instance('userRepository', $container->getService('userRepository'));
    

Common Patterns

Pattern Example
Factory Services $container->addFactory('cache', fn() => new \RedisCache());
Parameter Binding $container->addParameter('app.name', 'MyApp');
Dynamic Services $container->addService('user.123', new \App\User(123));
Locators $container->addLocator('repositories', fn($name) => new \App\Repo($name));

Gotchas and Tips

Pitfalls

  1. BC Breaks in v3.x

    • %parameters% is deprecated (use $container->getParameters()).
    • create($name) in LocatorDefinition is deprecated (use get()).
    • Union types require explicit handling in factories.
  2. Autowiring Quirks

    • Optional parameters with defaults are autowired differently in PHP 8 vs. 7.
    • Named arguments in constructors can conflict with positional autowiring.
    • Circular dependencies throw cryptic errors; use addService() for singletons.
  3. Configuration Issues

    • Neon/YAML syntax errors are silent until runtime. Validate with:
      composer validate-neon config.neon
      
    • Dynamic parameters (%foo%) must be defined in parameters section.
  4. Performance

    • Compiled containers (ContainerLoader) are faster but less flexible.
    • Avoid runtime service additions if using compiled mode.

Debugging Tips

  1. Tracy Panel Enable the DI panel for runtime inspection:

    $container->getService('tracy.bar')->addPanel(new \Nette\DI\ContainerPanel($container));
    
    • Shows service graph, dependencies, and configuration.
  2. Static Analysis Use PHPStan with nette/di’s PHPDoc:

    # phpstan.neon
    parameters:
        level: 8
        checkMissingIterableValueType: true
    
  3. Common Errors & Fixes

    Error Solution
    Service not found Check spelling, case sensitivity, or use getByType() for interfaces.
    Circular dependency Refactor into a factory or decorator.
    Type mismatch in autowiring Explicitly bind the service or use @inject in Neon.
    Neon parse error Validate with neon/neon CLI tool or enable strict_types.
    Lazy service not initialized Call $container->getService('name') to trigger lazy loading.

Extension Points

  1. Custom Extensions Extend CompilerExtension to add reusable logic:

    class CacheExtension extends CompilerExtension {
        public function loadConfiguration() {
            $builder = $this->getContainerBuilder();
            $builder->addService('cache', new \App\CacheService());
        }
    }
    
  2. Dynamic Service Factories Use closures for runtime-configured services:

    $container->addService('config', function () {
        return new \App\Config(['debug' => env('APP_DEBUG')]);
    });
    
  3. Parameter Expansion Dynamically resolve parameters:

    parameters:
        db.dsn: mysql:host=%env.DB_HOST%;dbname=%env.DB_NAME%
    
  4. Schema Validation Enforce service contracts with DefinitionSchema:

    $schema = new \Nette\Schema\Expect();
    $schema->add('type', 'string');
    $builder->addService('validator')
        ->setType('App\Validator')
        ->setArguments(['schema' => $schema]);
    

Pro Tips

  • Use getByType() for interfaces to avoid hardcoding service names.
  • Prefer addService() over addFactory() for singletons.
  • Leverage initialize() for post-construction setup:
    $container->getService('mailer')->initialize();
    
  • Enable strict_types=1 in PHP files for better type safety.
  • Cache compiled containers in production:
    $loader = new ContainerLoader(__DIR__.'/cache', ContainerLoader::MODE_CACHE);
    
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