YOLO DI is a lightweight PHP dependency injection (DI) library designed to simplify the process of managing dependencies, resolving classes, and injecting properties. It provides a static facade for interacting with the DI container, making it easy to bind, resolve, and manage object lifecycles.
- Dependency Resolution: Automatically resolve and instantiate classes with their dependencies.
- Class Binding: Bind interfaces or abstract classes to concrete implementations.
- Instance Management: Manually set or remove specific instances for classes.
- Alias Management: Create and manage aliases for classes.
- Custom Property Injection: Use attributes to inject custom dependencies into class properties.
To install YOLO DI, use Composer:
composer require yolo-fx/diuse Yolo\Di\DI;
DI::bind(LoggerInterface::class, ConsoleLogger::class);
$logger = DI::use(LoggerInterface::class);
$logger->log("Hello, World!");DI::alias(TestRunner::class, 'runner');
$runner = DI::use('runner');
$runner->sayHello();Define a custom attribute:
#[Attribute]
class Cache implements \Yolo\Di\PropertyAttributeInterface
{
public function __construct(private string $driver = 'default') {}
public function inject(): mixed
{
return match ($this->driver) {
'file' => DI::use(FileLogger::class),
default => DI::use(ConsoleLogger::class),
};
}
}Use the attribute in a class:
class TestRunner
{
public function __construct(
#[Cache('file')]
private LoggerInterface $logger
) {}
public function sayHello(): void
{
$this->logger->log("Hello, World!");
}
}- PHP 8.0 or higher
This project is licensed under the MIT License. See the LICENSE file for details.
- LUSHAOMING - lushaoming6@gmail.com