Performance: Dependency injection in controllers
This affects the server-side response time and memory usage, indirectly influencing page load speed by optimizing controller instantiation and reducing unnecessary object creation.
<?php class UserController extends Controller { protected UserService $service; public function __construct(UserService $service) { $this->service = $service; } public function index() { return $this->service->getAllUsers(); } }
<?php class UserController extends Controller { public function index() { $service = new UserService(); return $service->getAllUsers(); } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| New service instance inside method | N/A (server-side) | N/A | N/A | [X] Bad |
| Constructor dependency injection | N/A (server-side) | N/A | N/A | [OK] Good |
public function show(Service $service) {
return $service->greet();
}public function __construct(Service $service) {
$service = new Service();
$this->service = $service;
}Logger and Mailer, into a Laravel controller and use them in a method. Which constructor and method setup is correct?Pass the test and this pattern moves unknown