Lesson 4
30 min
Free Preview
Controllers & Routing
Handling requests with controllers
Controllers & Routing
Controllers receive HTTP requests and coordinate responses. Combined with routing, they form the backbone of request handling.
💡 RESTful Design
Following RESTful conventions makes your API predictable. Ginto AI generates RESTful controllers by default.
Basic Controller Structure
<?php
// src/Controllers/UserController.php
namespace App\Controllers;
use App\Models\User;
class UserController {
private User $userModel;
public function __construct(User $userModel) {
$this->userModel = $userModel;
}
// GET /users - List all users
public function index(): string {
$users = $this->userModel->all();
return view('users/index', ['users' => $users]);
}
// GET /users/{id} - Show single user
public function show(int $id): string {
$user = $this->userModel->find($id);
if (!$user) {
http_response_code(404);
return view('errors/404');
}
return view('users/show', ['user' => $user]);
}
// POST /users - Store new user
public function store(): void {
$data = [
'name' => $_POST['name'] ?? '',
'email' => $_POST['email'] ?? '',
'password' => $_POST['password'] ?? ''
];
$userId = $this->userModel->create($data);
header("Location: /users/{$userId}");
exit;
}
}
RESTful Route Conventions
| Method | URI | Action | Description |
|---|---|---|---|
GET |
/users | index | List all |
GET |
/users/create | create | Show form |
POST |
/users | store | Save new |
GET |
/users/{id} | show | Show one |
PUT |
/users/{id} | update | Update |
DELETE |
/users/{id} | destroy | Delete |
Route Definitions
<?php
// src/Routes/web.php
use App\Controllers\HomeController;
use App\Controllers\UserController;
// Home routes
$router->get('/', [HomeController::class, 'index']);
// User routes (RESTful)
$router->get('/users', [UserController::class, 'index']);
$router->get('/users/create', [UserController::class, 'create']);
$router->post('/users', [UserController::class, 'store']);
$router->get('/users/{id}', [UserController::class, 'show']);
$router->put('/users/{id}', [UserController::class, 'update']);
$router->delete('/users/{id}', [UserController::class, 'destroy']);
API Controller Example
<?php
// src/Controllers/Api/UserApiController.php
class UserApiController {
public function index(): void {
$users = $this->userModel->all();
header('Content-Type: application/json');
echo json_encode([
'success' => true,
'data' => $users
]);
}
public function show(int $id): void {
$user = $this->userModel->find($id);
if (!$user) {
http_response_code(404);
echo json_encode(['error' => 'Not found']);
return;
}
header('Content-Type: application/json');
echo json_encode(['success' => true, 'data' => $user]);
}
}
Useful Resources
🚀 Next Steps
In the next lesson, you'll learn how to create Views and implement templating.