Skip to content

Routes Configuration (routes.php) ​

The routes.php file lives in configs/ and is the single source of truth for all your JSON‑API endpoints. It returns an array of [method, path, handler] entries that the framework’s ApiRouter service will load and dispatch api response.


How Routing Works ​

  1. Route definitions are pulled in by the ApiRouter service when your API middleware invokes it.
  2. FastRoute compiles those definitions into a dispatcher.
  3. On each request, ApiMiddleware first applies your enabled/auth/throttle checks, then calls ApiRouter to match the path+method and invoke your handler.
  4. Your handler (a closure or [Class, method] pair) must return a ResponseInterface—typically a JsonResponse.

To summarize ​

  1. Create configs/routes.php.
  2. Define each endpoint with Route::get(...) style (or raw array entries).
  3. Return the routes array at the end of the file.
  4. Register your API middleware pipeline under the api alias in configs/middleware.php—it will automatically pick up routes.php.

How to Use ​

  1. Location Place routes.php in the configs/ directory of your application.

  2. Define Routes Use PHP array syntax or a small Route facade to declare all your API endpoints as [HTTP_METHOD, path, handler].

  3. Return Array At the end of routes.php, return the array of definitions. This is how the ApiRouter service knows what to load.

  4. Handlers

    • Closures: inline, quick logic returning a JsonResponse.
    • Controller pairs: [UserHandler::class, 'getUser']—the framework instantiates and calls them.

Configuration Overview ​

Key Array ElementDescriptionExample
MethodHTTP verb (GET, POST, PUT, DELETE, etc.).'GET'
PathURI pattern, supports FastRoute parameters (e.g. /{id:\d+}).'/users/{id:\d+}'
HandlerA PHP callable: closure, [Class::class, 'method'], or invokable object.function($req){...}, [UserHandler::class,'getUser']

Below are two equivalent ways to author your routes.php file.


1. Raw Array Format ​

Simply return a PHP array of triples. No facades or helpers required:

php
<?php
// configs/routes.php

use App\Http\Handlers\UserHandler;
use WPframework\Http\Message\JsonResponse;

return [
    // closure handler
    ['GET',    '/greeting', function () {
        return new JsonResponse(['message' => 'Hello World'], 200);
    }],

    // status endpoint
    ['GET',    '/status',   function () {
        return new JsonResponse([
            'uptime'   => (new DateTime())->format(DateTime::ATOM),
            'version'  => \App::VERSION,
        ], 200);
    }],

    // controller‑style routes
    ['GET',    '/users/{id:\d+}',    [UserHandler::class, 'getUser']],
    ['POST',   '/users',             [UserHandler::class, 'createUser']],
    ['PUT',    '/users/{id:\d+}',    [UserHandler::class, 'updateUser']],
    ['DELETE', '/users/{id:\d+}',    [UserHandler::class, 'deleteUser']],
];
  • Method: HTTP verb (GET, POST, etc.).

  • Path: FastRoute pattern (/users/{id:\d+}).

  • Handler:

    • A closure returning a JsonResponse (or any ResponseInterface).
    • A controller pair [ClassName::class, 'method'].

2. Facade‑Style Format ​

We can also use the Facade style Route::get(...) syntax and return them at the end:

php
<?php
// configs/routes.php

use WPframework\Support\Services\Route;
use App\Http\Handlers\UserHandler;
use WPframework\Http\Message\JsonResponse;

// Closure routes
Route::get('/greeting', function () {
    return new JsonResponse(['message' => 'Hello World'], 200);
});

Route::get('/status', function () {
    return new JsonResponse([
        'uptime'   => (new DateTime())->format(DateTime::ATOM),
        'version'  => \App::VERSION,
    ], 200);
});

// Controller‑style routes
Route::get('/users/{id:\d+}',    [UserHandler::class, 'getUser']);
Route::post('/users',            [UserHandler::class, 'createUser']);
Route::put('/users/{id:\d+}',    [UserHandler::class, 'updateUser']);
Route::delete('/users/{id:\d+}', [UserHandler::class, 'deleteUser']);

// **Finally, return the collected definitions:**
return Route::getRoutes();

How It All Ties Together ​

  1. ApiMiddleware (registered under the api alias) runs some checks: enabled‑flag, allowed methods, rate‑limit, auth, etc.

  2. Once those pass, it calls the ApiRouter service, which:

    • Loads configs/routes.php
    • Builds a FastRoute dispatcher from the returned array
    • Matches the incoming request and invokes your handler
  3. Handlers must return a ResponseInterface (typically JsonResponse).


Best Practices & Notes ​

  • One File – Unlike other configs, routing is not merged; this file is loaded exactly as‑is.
  • Patterns First – Define more specific routes before catch‑alls to avoid accidental matches.
  • Stateless Handlers – Keep your closures or controllers idempotent and side‑effect–free where possible.
  • Validation & Errors – Within your handlers, validate inputs and return appropriate HTTP codes (400, 404, 422, etc.).

Quick‑Start with Built‑In UserHandler ​

If you just want to kick the tyres and see JSON responses right away, the framework includes a dummy UserHandler you can use straight out of the box. Simply import it at the top of your configs/routes.php:

php
<?php
use WPframework\Support\Services\UserHandler;
use WPframework\Http\Message\JsonResponse;

Then map any user‑centric route to its methods:

php
return [
    // Fetch a fake user (returns id, name, email)
    ['GET', '/users/{id:\d+}', [UserHandler::class, 'getUser']],

    // Create a fake user (returns posted data plus an id)
    ['POST', '/users',             [UserHandler::class, 'createUser']],
];
  • No setup required—getUser() and createUser() will return dummy data for testing.
  • Mix and match with your own handlers or closures in the same file.
  • Great for verifying your API, routing, and JSON formatting in seconds!