How can dependency injection be utilized to improve the flexibility and maintainability of PHP front controller implementations?
Dependency injection can improve the flexibility and maintainability of PHP front controller implementations by decoupling the controller logic from its dependencies. This allows for easier testing, swapping out dependencies, and overall cleaner code organization.
class FrontController {
private $dependency;
public function __construct(Dependency $dependency) {
$this->dependency = $dependency;
}
public function handleRequest() {
// Controller logic using $this->dependency
}
}
$dependency = new Dependency();
$frontController = new FrontController($dependency);
$frontController->handleRequest();