Title here
Summary here
The Norvica DI Container provides a convenient way to invoke any callable (function, method, or class with __invoke()
)
while automatically injecting its dependencies. This can be particularly useful for executing commands, running
background tasks, or triggering specific actions in your application.
When you invoke a callable through using container as a callable itself, it will inspect the callable’s parameters and automatically resolve any dependencies it can find registered in the container.
Besides injecting dependencies, you can also pass additional parameters to the call:
$result = $container(MyCallable::class, extraArg: 'value');
// or
$result = $container->__invoke(MyCallable::class, extraArg: 'value');
Let’s illustrate how to invoke different types of callables.
__invoke()
Methodclass MyCommand {
public function __construct(LoggerInterface $logger) { /* ... */ }
public function __invoke(string $message) {
$this->logger->info($message);
}
}
// ...
$container(MyCommand::class, message: 'Command is executed.');
// or
$container->__invoke(MyCommand::class, message: 'Command is executed.');
use function Norvica\Container\ref;
class MyService {
public function processData(string $data) { /* ... */ }
}
// ...
$container([ref(MyService::class), 'processData'], data: 'some_data');
// or
$container->__invoke([ref(MyService::class), 'processData'], data: 'some_data');
class Utils {
public static function generateReport(PDO $db, string $startDate, string $endDate) { /* ... */ }
}
// ...
$container(Utils::generateReport(...), startDate: '2024-01-01', endDate: '2024-01-31');
// or
$container->__invoke(Utils::generateReport(...), startDate: '2024-01-01', endDate: '2024-01-31');
$container(
function (LoggerInterface $logger, string $message) {
$logger->info($message);
},
message: 'Logging a message from the closure',
);
// or
$container->__invoke(
function (LoggerInterface $logger, string $message) {
$logger->info($message);
},
message: 'Logging a message from the closure',
);