How can the process of automating and optimizing class calls/dependencies in controllers be improved in PHP?
When working with controllers in PHP, it can be tedious to manually manage class calls and dependencies. To automate and optimize this process, we can utilize dependency injection to pass required classes to the controller constructor, reducing the need for manual instantiation within the controller methods.
// Example of automating class calls/dependencies in controllers using dependency injection
class UserController {
private $userService;
public function __construct(UserService $userService) {
$this->userService = $userService;
}
public function getUserById($userId) {
$user = $this->userService->getUserById($userId);
// Further logic here
}
}
// Usage example
$userService = new UserService();
$userController = new UserController($userService);
$userController->getUserById(123);