How can a Dependency Injection Container like PHP-DI be utilized effectively in PHP routing and dispatching?
When using PHP routing and dispatching, a Dependency Injection Container like PHP-DI can be utilized effectively by allowing the container to manage the instantiation and injection of dependencies for each route handler. This helps in keeping the code clean, organized, and maintainable by centralizing the configuration of dependencies.
// Create a container instance
$container = new DI\Container();
// Define dependencies
$container->set('Logger', function() {
return new Logger();
});
// Define a route handler
$container->set('HomeController', function($container) {
return new HomeController($container->get('Logger'));
});
// Route dispatching
$route = $_GET['route'];
switch ($route) {
case 'home':
$controller = $container->get('HomeController');
$controller->index();
break;
// Add more cases for other routes
}