How can the use of a Dependency Container simplify the process of managing and accessing dependencies in PHP controllers?

When working with PHP controllers, managing and accessing dependencies can become complex as the application grows. Utilizing a Dependency Container can simplify this process by centralizing the configuration and instantiation of dependencies. This allows controllers to easily access the required dependencies without having to manage them individually.

// Creating a Dependency Container
$container = new Container();

// Registering dependencies
$container->set('db', function() {
    return new Database();
});

$container->set('logger', function() {
    return new Logger();
});

// Accessing dependencies in a controller
class UserController {
    protected $db;
    protected $logger;

    public function __construct(Container $container) {
        $this->db = $container->get('db');
        $this->logger = $container->get('logger');
    }

    public function index() {
        // Accessing the database and logger
        $this->db->query('SELECT * FROM users');
        $this->logger->log('User data retrieved');
    }
}

// Instantiating the controller with the Dependency Container
$userController = new UserController($container);
$userController->index();