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
- Route definitions are pulled in by the ApiRouter service when your API middleware invokes it.
- FastRoute compiles those definitions into a dispatcher.
- On each request, ApiMiddleware first applies your enabled/auth/throttle checks, then calls ApiRouter to match the path+method and invoke your handler.
- Your handler (a closure or
[Class, method]
pair) must return aResponseInterface
—typically aJsonResponse
.
To summarize
- Create
configs/routes.php
. - Define each endpoint with
Route::get(...)
style (or raw array entries). - Return the routes array at the end of the file.
- Register your API middleware pipeline under the
api
alias inconfigs/middleware.php
—it will automatically pick uproutes.php
.
How to Use
Location Place
routes.php
in theconfigs/
directory of your application.Define Routes Use PHP array syntax or a small
Route
facade to declare all your API endpoints as[HTTP_METHOD, path, handler]
.Return Array At the end of
routes.php
,return
the array of definitions. This is how the ApiRouter service knows what to load.Handlers
- Closures: inline, quick logic returning a
JsonResponse
. - Controller pairs:
[UserHandler::class, 'getUser']
—the framework instantiates and calls them.
- Closures: inline, quick logic returning a
Configuration Overview
Key Array Element | Description | Example |
---|---|---|
Method | HTTP verb (GET , POST , PUT , DELETE , etc.). | 'GET' |
Path | URI pattern, supports FastRoute parameters (e.g. /{id:\d+} ). | '/users/{id:\d+}' |
Handler | A 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
// 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 anyResponseInterface
). - A controller pair
[ClassName::class, 'method']
.
- A closure returning a
2. Facade‑Style Format
We can also use the Facade style Route::get(...)
syntax and return them at the end:
<?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
ApiMiddleware
(registered under theapi
alias) runs some checks: enabled‑flag, allowed methods, rate‑limit, auth, etc.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
- Loads
Handlers must return a
ResponseInterface
(typicallyJsonResponse
).
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
use WPframework\Support\Services\UserHandler;
use WPframework\Http\Message\JsonResponse;
Then map any user‑centric route to its methods:
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()
andcreateUser()
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!