Jednoduché API ve frameworku Slim 4 – č. 5 Vylepšení UserControlleru
- Jednoduché API ve frameworku Slim 4 – č. 1 Instalace
- Jednoduché API ve frameworku Slim 4 – č. 2 Základní CRUD
- Jednoduché API ve frameworku Slim 4 – č. 3 Struktura API a připojení k databázi
- Jednoduché API ve frameworku Slim 4 – č. 4 Testování funkcionality našeho malého API
- Jednoduché API ve frameworku Slim 4 – č. 5 Vylepšení UserControlleru
- Jednoduché API ve frameworku Slim 4 – č. 6 Přidání Model a Repositories
- Jednoduché API ve frameworku Slim 4 – č. 7 Validace dat
- Jednoduché API ve frameworku Slim 4 – č. 8 Přidáme si do datbáze produkty
Naše API funguje, ale můžeme zkusit ještě vylepšit, třeba si přidáme validaci vstupních, přidáme prepared statement po práci s databází
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 |
<?php namespace App\Controllers; use PDO; use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Exception\HttpNotFoundException; use Slim\Exception\HttpBadRequestException; class UserController { private PDO $db; public function __construct(PDO $db) { $this->db = $db; } private function jsonResponse(Response $response, mixed $data, int $status = 200): Response { $response->getBody()->write(json_encode($data, JSON_THROW_ON_ERROR)); return $response ->withHeader('Content-Type', 'application/json') ->withStatus($status); } private function validateUserData(array $data): void { if (empty($data['name']) || empty($data['email'])) { throw new HttpBadRequestException(null, 'Name and email are required'); } if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) { throw new HttpBadRequestException(null, 'Invalid email format'); } } public function getAll(Request $request, Response $response): Response { try { $stmt = $this->db->query('SELECT * FROM users'); $users = $stmt->fetchAll(PDO::FETCH_ASSOC); return $this->jsonResponse($response, $users); } catch (\PDOException $e) { throw new \RuntimeException('Database error: ' . $e->getMessage()); } } public function getOne(Request $request, Response $response, array $args): Response { try { $stmt = $this->db->prepare('SELECT * FROM users WHERE id = ?'); $stmt->execute([$args['id']]); $user = $stmt->fetch(PDO::FETCH_ASSOC); if (!$user) { throw new HttpNotFoundException($request, 'User not found'); } return $this->jsonResponse($response, $user); } catch (\PDOException $e) { throw new \RuntimeException('Database error: ' . $e->getMessage()); } } public function create(Request $request, Response $response): Response { try { $data = $request->getParsedBody(); $this->validateUserData($data); $stmt = $this->db->prepare('INSERT INTO users (name, email) VALUES (:name, :email)'); $stmt->execute([ ':name' => $data['name'], ':email' => $data['email'] ]); $user = [ 'id' => $this->db->lastInsertId(), 'name' => $data['name'], 'email' => $data['email'] ]; return $this->jsonResponse($response, $user, 201); } catch (\PDOException $e) { // Check for duplicate email if ($e->getCode() == 23000) { // MySQL duplicate entry error throw new HttpBadRequestException($request, 'Email already exists'); } throw new \RuntimeException('Database error: ' . $e->getMessage()); } } public function update(Request $request, Response $response, array $args): Response { try { $data = $request->getParsedBody(); $this->validateUserData($data); // Begin transaction $this->db->beginTransaction(); // Check if user exists $checkStmt = $this->db->prepare('SELECT id FROM users WHERE id = ? FOR UPDATE'); $checkStmt->execute([$args['id']]); if (!$checkStmt->fetch()) { $this->db->rollBack(); throw new HttpNotFoundException($request, 'User not found'); } // Update user $stmt = $this->db->prepare('UPDATE users SET name = :name, email = :email WHERE id = :id'); $stmt->execute([ ':name' => $data['name'], ':email' => $data['email'], ':id' => $args['id'] ]); // Get updated user $stmt = $this->db->prepare('SELECT * FROM users WHERE id = ?'); $stmt->execute([$args['id']]); $user = $stmt->fetch(PDO::FETCH_ASSOC); $this->db->commit(); return $this->jsonResponse($response, $user); } catch (\PDOException $e) { $this->db->rollBack(); if ($e->getCode() == 23000) { throw new HttpBadRequestException($request, 'Email already exists'); } throw new \RuntimeException('Database error: ' . $e->getMessage()); } } public function delete(Request $request, Response $response, array $args): Response { try { $this->db->beginTransaction(); $checkStmt = $this->db->prepare('SELECT id FROM users WHERE id = ? FOR UPDATE'); $checkStmt->execute([$args['id']]); if (!$checkStmt->fetch()) { $this->db->rollBack(); throw new HttpNotFoundException($request, 'User not found'); } $stmt = $this->db->prepare('DELETE FROM users WHERE id = ?'); $stmt->execute([$args['id']]); $this->db->commit(); return $response->withStatus(204); } catch (\PDOException $e) { $this->db->rollBack(); throw new \RuntimeException('Database error: ' . $e->getMessage()); } } } |