JSON yanıt formatı
Başarılı ve hata yanıtları için tutarlı JSON formatı yazarsın.
JsonResponse sınıfı
Bir REST API tutarlı bir yanıt formatına ihtiyaç duyar. JsonResponse sınıfı bunu sağlar: bir durum kodu (200, 201, 400, 404) ve bir gövde dizisi tutar. send() yöntemi üç şey yapar: http_response_code() ile durum kodunu, header() ile içerik türünü, json_encode() ile gövdeyi yapısal veri olarak döndürür.
Böylece her işleyici aynı formatı üretir; istemci ayrıştırmakta zorlanmaz.
Durum kodları
HTTP durum kodları yanıtın anlamını taşır. 200 başarılı, 201 oluşturuldu, 400 geçersiz istek, 404 bulunamadı demektir. JsonResponse yapıcısı bu kodu ilk parametre olarak alır.
Başarılı bir okuma 200, yeni kayıt oluşturma 201 döndürür. Eksik veya bozuk istekler 400, var olmayan kaynak 404 ile yanıtlanır. İstemci yalnızca koda bakarak sonucu yorumlar.
Uygulama JsonResponse sınıfını tanımla
JsonResponse adında bir sınıf tanımla. İki property ekle: public int $status; ve public array $body;. Bir __construct(int $status, array $body) yapıcısı ile bu property'lere ata. Bir send() yöntemi yaz: http_response_code($this->status) ve header("Content-Type: application/json") çağrılarını yapsın ve return json_encode($this->body, JSON_UNESCAPED_UNICODE); döndürsün. Demo bir örnek oluşturup send() çıktısını yazdırır.
Örnek çözümü göster
application/json"); return json_encode($this->body, JSON_UNESCAPED_UNICODE); yaz.
Örnek çözüm:
<?php
// REST API projesi: Router + addRoute + dispatch + JsonResponse
class Router {
public array $routes = [];
public function addRoute(string $method, string $path, $handler): void {
$this->routes[] = ["method" => $method, "path" => $path, "handler" => $handler];
}
public function dispatch(string $method, string $path) {
foreach ($this->routes as $route) {
if ($route["method"] === $method && $route["path"] === $path) {
return ($route["handler"])();
}
}
return "404 Bulunamadı";
}
}
class JsonResponse {
public int $status;
public array $body;
public function __construct(int $status, array $body) {
$this->status = $status;
$this->body = $body;
}
public function send(): string {
http_response_code($this->status);
header("Content-Type: application/json");
return json_encode($this->body, JSON_UNESCAPED_UNICODE);
}
}
// Demo:
$resp = new JsonResponse(200, ["message" => "Tamam"]);
echo $resp->send();
Kendini test et
-
JsonResponse::send() yöntemi hangi üç aracı sırayla kullanır?
- echo, print ve var_dump
- count, sort ve array_map
- fopen, fwrite ve fclose
- http_response_code, header ve json_encode
Cevabı göster
http_response_code, header ve json_encode — Doğru. send() önce durum kodunu, sonra başlığı, en son gövdeyi yapısal veriye çevirir.
-
Durum kodlarını eşleştir
- 200
- Başarılı
- 201
- Oluşturuldu
- 400
- Geçersiz istek
- 404
- Bulunamadı
-
İçerik türü başlığını tamamla
header("____");Cevabı göster
header("Content-Type: application/json");