PHP โปรเจกต์: REST API สมุดโน้ต



โปรเจกต์นี้สร้าง API สำหรับจัดการโน้ต — CRUD ครบ ตอบเป็น JSON ใช้ PHP ล้วน (ไม่มีเฟรมเวิร์ก) เพื่อให้เห็นว่าทุกชิ้นทำงานยังไง

สิ่งที่จะได้

GET    /notes           รายการโน้ตทั้งหมด
GET    /notes/{id}       โน้ตเดียว
POST   /notes            สร้าง (body: JSON {title, body})
PUT    /notes/{id}       แก้ไข
DELETE /notes/{id}       ลบ

โครงสร้าง

notes-api/
├── public/index.php
├── src/
│   ├── Database.php
│   ├── NoteRepository.php
│   ├── Validator.php
│   └── Router.php
├── schema.sql
└── composer.json
{
    "require": { "php": ">=8.3" },
    "autoload": { "psr-4": { "App\\": "src/" } }
}
composer dump-autoload

schema.sql

CREATE TABLE IF NOT EXISTS notes (
    id         INTEGER PRIMARY KEY AUTOINCREMENT,
    title      TEXT NOT NULL,
    body       TEXT NOT NULL DEFAULT '',
    created_at TEXT NOT NULL DEFAULT (datetime('now')),
    updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);

src/Database.php

<?php
declare(strict_types=1);

namespace App;

use PDO;

final class Database
{
    public static function connect(string $path): PDO
    {
        $isNew = !is_file($path);

        $pdo = new PDO('sqlite:' . $path, null, null, [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        $pdo->exec('PRAGMA foreign_keys = ON');

        if ($isNew) {
            $pdo->exec(file_get_contents(__DIR__ . '/../schema.sql'));
        }
        return $pdo;
    }
}

src/NoteRepository.php

<?php
declare(strict_types=1);

namespace App;

use PDO;

final class NoteRepository
{
    public function __construct(private PDO $pdo) {}

    /** @return list<array<string,mixed>> */
    public function all(): array
    {
        return $this->pdo
            ->query('SELECT * FROM notes ORDER BY id DESC')
            ->fetchAll();
    }

    public function find(int $id): ?array
    {
        $stmt = $this->pdo->prepare('SELECT * FROM notes WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->fetch() ?: null;
    }

    public function create(string $title, string $body): array
    {
        $stmt = $this->pdo->prepare(
            'INSERT INTO notes (title, body) VALUES (:t, :b)'
        );
        $stmt->execute(['t' => $title, 'b' => $body]);
        return $this->find((int) $this->pdo->lastInsertId());
    }

    public function update(int $id, string $title, string $body): ?array
    {
        $stmt = $this->pdo->prepare(
            "UPDATE notes SET title = :t, body = :b, updated_at = datetime('now')
             WHERE id = :id"
        );
        $stmt->execute(['t' => $title, 'b' => $body, 'id' => $id]);
        return $stmt->rowCount() > 0 || $this->find($id) ? $this->find($id) : null;
    }

    public function delete(int $id): bool
    {
        $stmt = $this->pdo->prepare('DELETE FROM notes WHERE id = ?');
        $stmt->execute([$id]);
        return $stmt->rowCount() > 0;
    }
}

src/Validator.php

<?php
declare(strict_types=1);

namespace App;

final class Validator
{
    /**
     * @param array<string,mixed> $data
     * @return array{0: array{title:string, body:string}, 1: array<string,string>}
     */
    public static function note(array $data): array
    {
        $errors = [];

        $title = trim((string) ($data['title'] ?? ''));
        if ($title === '') {
            $errors['title'] = 'ต้องระบุหัวข้อ';
        } elseif (mb_strlen($title) > 200) {
            $errors['title'] = 'หัวข้อยาวเกิน 200 ตัวอักษร';
        }

        $body = trim((string) ($data['body'] ?? ''));
        if (mb_strlen($body) > 10000) {
            $errors['body'] = 'เนื้อหายาวเกินไป';
        }

        return [['title' => $title, 'body' => $body], $errors];
    }
}

src/Router.php

<?php
declare(strict_types=1);

namespace App;

final class Router
{
    /** @var list<array{method:string,regex:string,handler:callable}> */
    private array $routes = [];

    public function add(string $method, string $path, callable $handler): void
    {
        $regex = '#^' . preg_replace('#\{(\w+)\}#', '(?<$1>[^/]+)', $path) . '$#';
        $this->routes[] = compact('method', 'regex', 'handler');
    }

    public function dispatch(string $method, string $path): void
    {
        foreach ($this->routes as $r) {
            if ($r['method'] === $method && preg_match($r['regex'], $path, $m)) {
                $params = array_filter($m, 'is_string', ARRAY_FILTER_USE_KEY);
                ($r['handler'])($params);
                return;
            }
        }
        self::json(['error' => 'ไม่พบ endpoint นี้'], 404);
    }

    public static function json(mixed $data, int $status = 200): void
    {
        http_response_code($status);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        exit;
    }

    /** @return array<string,mixed> */
    public static function jsonBody(): array
    {
        $raw = file_get_contents('php://input');
        if ($raw === '' || $raw === false) {
            return [];
        }
        try {
            $data = json_decode($raw, true, flags: JSON_THROW_ON_ERROR);
        } catch (\JsonException) {
            self::json(['error' => 'JSON ไม่ถูกต้อง'], 400);
        }
        return is_array($data) ? $data : [];
    }
}

public/index.php

<?php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

use App\{Database, NoteRepository, Router, Validator};

header('Content-Type: application/json; charset=utf-8');

set_exception_handler(function (\Throwable $e): void {
    error_log((string) $e);
    Router::json(['error' => 'เกิดข้อผิดพลาดภายในเซิร์ฟเวอร์'], 500);
});

$pdo = Database::connect(__DIR__ . '/../storage/notes.db');
$repo = new NoteRepository($pdo);
$router = new Router();

$router->add('GET', '/notes', function () use ($repo): void {
    Router::json(['data' => $repo->all()]);
});

$router->add('GET', '/notes/{id}', function (array $p) use ($repo): void {
    $note = $repo->find((int) $p['id']);
    $note ? Router::json(['data' => $note]) : Router::json(['error' => 'ไม่พบโน้ต'], 404);
});

$router->add('POST', '/notes', function () use ($repo): void {
    [$clean, $errors] = Validator::note(Router::jsonBody());
    if ($errors) {
        Router::json(['errors' => $errors], 422);
    }
    Router::json(['data' => $repo->create($clean['title'], $clean['body'])], 201);
});

$router->add('PUT', '/notes/{id}', function (array $p) use ($repo): void {
    $id = (int) $p['id'];
    if (!$repo->find($id)) {
        Router::json(['error' => 'ไม่พบโน้ต'], 404);
    }
    [$clean, $errors] = Validator::note(Router::jsonBody());
    if ($errors) {
        Router::json(['errors' => $errors], 422);
    }
    Router::json(['data' => $repo->update($id, $clean['title'], $clean['body'])]);
});

$router->add('DELETE', '/notes/{id}', function (array $p) use ($repo): void {
    $repo->delete((int) $p['id'])
        ? Router::json(['message' => 'ลบแล้ว'])
        : Router::json(['error' => 'ไม่พบโน้ต'], 404);
});

$router->dispatch(
    $_SERVER['REQUEST_METHOD'],
    rtrim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/') ?: '/notes',
);

รันและทดสอบ

mkdir -p storage
php -S localhost:8000 -t public
# สร้าง
curl -s -X POST localhost:8000/notes \
  -H 'Content-Type: application/json' \
  -d '{"title":"ซื้อของ","body":"นม, ไข่, ขนมปัง"}'
{
    "data": {
        "id": 1,
        "title": "ซื้อของ",
        "body": "นม, ไข่, ขนมปัง",
        "created_at": "2026-09-07 08:00:00",
        "updated_at": "2026-09-07 08:00:00"
    }
}
curl -s localhost:8000/notes                       # รายการ
curl -s localhost:8000/notes/1                      # ตัวเดียว
curl -s -X PUT localhost:8000/notes/1 -d '{"title":"","body":"x"}'   # -> 422
curl -s -X DELETE localhost:8000/notes/1            # ลบ
curl -s -i localhost:8000/notes/999                 # -> 404
HTTP/1.1 422 Unprocessable Content
{"errors":{"title":"ต้องระบุหัวข้อ"}}

จุดที่ใช้ความรู้จากบทก่อน

ส่วนบท
อ่าน php://input, status code, header29
validation คืน error เป็นอาร์เรย์31
PDO + prepared statement + repository36–38
namespace + PSR-4 autoload22, 25
front controller + router43
set_exception_handler, JSON error24, 28

ต่อยอด

  • auth — เพิ่ม Authorization: Bearer header + ตาราง api_tokens (ทำในโปรเจกต์ที่ 45)
  • pagination — GET /notes?page=2 ด้วย LIMIT/OFFSET + COUNT(*)
  • เทสต์ — NoteRepositoryTest ด้วย sqlite::memory: (บทที่ 26)
  • เปลี่ยนเป็น MySQL — แก้แค่ Database::connect() โค้ดที่เหลือไม่ต้องแตะ (นี่คือประโยชน์ของ PDO)

เรื่องที่คนมักพลาด

  • ไม่ตั้ง Content-Type: application/json — client บางตัวตีความ response ผิด
  • คืน 200 ตลอด แม้ error — ใช้ status code ให้ถูก: 201 สร้าง, 404 ไม่พบ, 422 validate ไม่ผ่าน, 400 JSON เสีย, 500 error ระบบ
  • ลืม exit ใน Router::json() — โค้ดถัดไปทำงานต่อ ส่ง JSON ซ้อน
  • เก็บ notes.db ใน public/ — ดาวน์โหลดฐานข้อมูลทั้งไฟล์ได้ วางใน storage/
  • echo ค่าจาก DB กลับไปโดยไม่ระวัง — ใน JSON API json_encode escape ให้แล้ว แต่ถ้าเอาไปแสดงใน HTML ต้อง htmlspecialchars อีกชั้น

สรุป

  • REST API = URL + HTTP method → controller → repository → JSON + status code ที่ถูกต้อง
  • router เขียนเองไม่ถึง 40 บรรทัด: แปลง /notes/{id} เป็น regex, จับ named group เป็น params
  • แยกชั้น: Database (เชื่อมต่อ) / Repository (SQL) / Validator (กฎ) / Router (dispatch) / index.php (ประกอบ)
  • PDO ทำให้เปลี่ยน SQLite → MySQL ได้โดยแก้จุดเดียว
  • ทดสอบด้วย curl -i ดู status + body

บทถัดไป โปรเจกต์ระบบสมาชิก — สมัคร/ล็อกอินด้วย session, password_hash, middleware ป้องกันเส้นทาง และ CSRF