Kotchasan Framework Documentation

Kotchasan Framework Documentation

การจัดการ API และ Middleware

TH 04 Feb 2026 03:48

การจัดการ API และ Middleware

เอกสารส่วนนี้รวบรวมแนวทางการพัฒนา RESTful API ด้วย Kotchasan Framework รวมถึงการใช้งานระบบ Middleware เพื่อจัดการ Authentication และ Security

ส่วนประกอบหลัก

1. ApiController

Base Controller สำหรับสร้าง API Endpoints รองรับการจัดการ Request, Validation และ Standard Response

2. Middleware System

ระบบจัดการ HTTP Request/Response แบบเป็นชั้น (Layered) สำหรับทำ Authentication, Logging, CORS ฯลฯ

3. ApiException

มาตรฐานการจัดการข้อผิดพลาด (Error Handling) และการส่ง HTTP Status Code ที่ถูกต้อง

ตัวอย่างการใช้งานระบบ API (Integration Guide)

ส่วนนี้แสดงตัวอย่างการนำส่วนประกอบต่างๆ (Controller, Middleware, Routing) มาทำงานร่วมกันเพื่อสร้างระบบ API ที่สมบูรณ์

โครงสร้าง REST API พื้นฐาน

// api/v1/user.php
use Kotchasan\ApiController;
use Kotchasan\Http\Request;

class UserController extends ApiController
{
    /**
     * GET /users
     * แสดงรายการผู้ใช้
     */
    public function index(Request $request)
    {
        // 1. Validate Method
        if (!self::validateMethod($request, 'GET')) {
            throw new \Kotchasan\ApiException('Method Not Allowed', 405);
        }

        // 2. Auth Check (Example)
        $token = $this->getAccessToken($request);
        if (!$token) {
            throw new \Kotchasan\ApiException('Unauthorized', 401);
        }

        // 3. Logic
        $users = ['User A', 'User B'];

        // 4. Response
        return $this->successResponse($users);
    }
}

การใช้งาน Middleware Pipeline

การนำ Middleware หลายตัวมาต่อกันเพื่อกรอง Request ก่อนเข้าสู่ Controller

use Kotchasan\Http\Request;
use Kotchasan\Http\Middleware\CorsMiddleware;
use Kotchasan\Http\Middleware\JwtMiddleware;
use App\Api\UserController;

// Setup Middleware
$pipeline = new \Kotchasan\Http\Middleware\Pipeline();

$pipeline->pipe(new CorsMiddleware(['*'])); // 1. CORS
$pipeline->pipe(new JwtMiddleware('secret')); // 2. Auth

// Handle Request
$response = $pipeline->process($request, function($req) {
    // Controller Dispatcher
    $controller = new UserController();
    return $controller->index($req);
});

$response->send();

Best Practices

  1. Versioning: ควรระบุ version ใน URL เสมอ เช่น /api/v1/...
  2. Stateless: API ควรเป็น Stateless (ไม่เก็บ Session) และใช้ Token แทน
  3. HTTP Verbs: ใช้ GET, POST, PUT, DELETE ให้ถูกต้องตามความหมาย
  4. Error Codes: ใช้ HTTP Status Code ให้ถูกต้อง (200, 201, 400, 401, 403, 404, 500)
  5. Security: ตรวจสอบ HTTPS, Validate Input, และกรอง Output เสมอ