Kotchasan Framework Documentation

Kotchasan Framework Documentation

Router

EN 05 Feb 2026 06:23

Router

Kotchasan\Router is the Core Router Class responsible for MVC Routing and URL Parsing. It maps URLs to specific Modules, Controllers, and Methods based on defined rules.

[!NOTE]
For Modern RESTful API Routing (GET, POST, Group), please refer to Http\Router.

Basic Usage

Typically initialized in index.php to bootstrap the application:

// index.php
use Kotchasan\Router;

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

Routes and Rules

The Router uses Regex to match URLs and extract components.

1. API Route

Handles URLs starting with /api or api.php.

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

  • URL: /api/v1/user/get-token
  • Result:
    • _dir = 'api'
    • module = 'v1'
    • method = 'user'
    • action = 'getToken' (Dash converted to CamelCase)

2. MVC Route

Standard MVC structure via 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' (No CamelCase conversion)

[!WARNING]
MVC Routes DO NOT support dashes (-) in the dir or method segments. Additionally, underscores (_) are NOT converted to CamelCase. If you use update_item in the URL, your controller method must be function update_item().

3. Module Route

Direct module access with alias.

Format: /{module}/{alias}

  • URL: /user/edit-profile
  • Result:
    • module = 'user'
    • alias = 'editProfile' (Converted to CamelCase)

Methods

init(string $className): static

Initializes the router and dispatches the request to the target controller.

  • $className: The Default Controller Class to use if no route is matched (Home page).

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

Parses a URL path into an array of parameters.

  • $path: URL Path (e.g., /api/v1/test)
  • $modules: Initial modules array (usually $_GET)
  • Returns: Array containing extracted URL parameters.

Examples

API Example

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

MVC Example

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

Gotchas

  1. Dash in MVC: Do not use dashes (-) in _dir or _method segments of MVC Routes. The regex pattern [a-z0-9_]+ does not allow them.
  2. CamelCase Conversion:
    • API Routes: get-token -> getToken (Supported)
    • Module Alias: edit-profile -> editProfile (Supported)
    • MVC Routes: update_item -> update_item (No conversion)