nette/di
Nette DI is a fast, secure dependency injection container for PHP. It compiles configuration into optimized PHP for performance, supports autowiring, service factories, extensions, and strong type safety. Ideal for Nette apps or standalone use.
Start by installing via Composer: composer require nette/di. Define services in a NEON config file (e.g., services.neon) using simple key-value syntax—Nette auto-detects services by type-hints and uses autowiring by default. For a basic setup:
services:
- App\Model\UserRepository
App\Service\EmailService: [@App\Model\UserRepository]
parameters:
debugMode: %env.ADAPTIVE_DEBUG%
Then compile the container:
$compiler = new Nette\DI\Compiler();
$compiler->addConfig(['services' => [...]]); // or load from NEON
$container = $compiler->compile();
First use case: inject services via constructor autowiring in your classes—no configuration needed for most cases.
services:
cacheFactory:
factory: App\Factory\CacheFactory::create()
setup:
- setTtl(3600)
%env.VAR% or parameters section—expanded at compile time for performance.lazy: true to defer instantiation until first use:
services:
dbConnection:
lazy: true
factory: PDO
Nette\DI\CompilerExtension to register service definitions programmatically (e.g., bundling related services like Doctrine or logging).#[Nette\DI\Attributes\Inject] on properties/methods for injection where constructors are impractical (e.g., controllers).class option renamed to type in earlier versions; reverse in v3.1.8+. Verify config keys.%parameters% expands only static params—avoid for runtime values. Use getParameter() at runtime instead.Resolver may silently fail on ambiguous mixed or object type hints—explicit nullable types (?Type) or union types improve reliability.@self prefix for setup helps with self-references.ContainerBuilder::$tempDir)—reduces cold-start overhead from ~200ms to near-zero.Container::getService('debug Tracy') or inspect $container->getByType(...) outputs with Container::dump()—great for troubleshooting service definitions.array<ClassName> or list<ClassName> annotations for collections over raw array.lazy and group infrequently loaded extensions in separate config files—reduces compiled container size and compile time significantly.How can I help you explore Laravel packages today?