Kotchasan Framework Documentation

Kotchasan Framework Documentation

Router

TH 05 Feb 2026 06:23

Router

Kotchasan\Router เป็น Core Router Class ทำหน้าที่จัดการ MVC Routing และ URL Parsing สำหรับ Application ทั่วไป รองรับการแปลง URL เป็น Controller Module และ Method ตามกฎที่กำหนด

[!NOTE]
สำหรับ RESTful API Routing แบบ Modern (GET, POST, Group) กรุณาดูที่ Http\Router

การใช้งานพื้นฐาน

โดยปกติ Router จะถูกเรียกใช้ใน index.php เพื่อเริ่มต้นระบบ:

// index.php
use Kotchasan\Router;

$router = new Router;
$router->init('Gcms\Controller');

เส้นทาง (Routes) และกฎ (Rules)

Router ใช้ Regex ในการจับคู่ URL และแยกส่วนประกอบ (Components) ออกมาใช้งาน

1. API Route

รองรับ URL ที่ขึ้นต้นด้วย /api หรือ api.php

Format: /api/{version}/{module}/{method}/{action}

  • URL: /api/v1/user/get-token
  • Result:
    • _dir = 'api'
    • module = 'v1'
    • method = 'user'
    • action = 'getToken' (แปลง Dash เป็น CamelCase)

2. MVC Route

รองรับโครงสร้าง MVC มาตรฐานผ่าน index.php

Format: /index.php/{module}/{type}/{dir}/{method}

  • URL: /index.php/inventory/controller/stock/update_item
  • Result:
    • module = 'inventory'
    • _mvc = 'controller'
    • _dir = 'stock'
    • _method = 'update_item' (ไม่แปลงเป็น CamelCase)

[!WARNING]
MVC Route ไม่รองรับ เครื่องหมาย Dash (-) ในชื่อ Method และ ไม่มี การแปลง Underscore (_) เป็น CamelCase หากใช้ Underscore ใน URL ชื่อ Method ใน Controller ก็ต้องเป็น Underscore ด้วย (function update_item())

3. Module Route

สำหรับเรียก Module ตรงๆ

Format: /{module}/{alias}

  • URL: /user/edit-profile
  • Result:
    • module = 'user'
    • alias = 'editProfile' (แปลงเป็น CamelCase)

Methods

init(string $className): static

เริ่มต้น Router และ Dispatch ไปยัง Controller เป้าหมาย

  • $className: Default Controller Class หากไม่พบ Route (เช่น หน้า Home)

parseRoutes(string $path, array $modules): array

แปลง URL Path เป็น Array ของ Parameters (ใช้ภายใน Class แต่เป็น Public)

  • $path: URL Path (เช่น /api/v1/test)
  • $modules: Array เริ่มต้น (ปกติใช้ $_GET)
  • Returns: Array ที่รวม URL Params เข้าไปแล้ว

ตัวอย่างการทำงาน

กรณี API

$router->parseRoutes('/api/v1/auth/login', []);
// Returns: ['_dir'=>'api', 'module'=>'v1', 'method'=>'auth', 'action'=>'login']

กรณี MVC

$router->parseRoutes('/index.php/shop/model/cart/add_item', []);
// Returns: ['module'=>'shop', '_mvc'=>'model', '_dir'=>'cart', '_method'=>'add_item']

ข้อควรระวัง (Gotchas)

  1. Dash in MVC: ห้ามใช้ Dash (-) ในส่วนของ _dir หรือ _method ใน MVC Route เพราะ Regex ไม่รองรับ ([a-z0-9_]+)
  2. CamelCase Conversion:
    • API Route: แปลง get-token -> getToken (Automatic)
    • Module Alias: แปลง edit-profile -> editProfile (Automatic)
    • MVC Route: ไม่แปลง update_item -> update_item (Manual)