Repository navigation
Routing & mouse RPC Documentation
The mouse-php routing engine is engineered around a single core priority: uncompromising execution speed.
Instead of relying on heavy Regular Expression (Regex) evaluation loops that parse routes sequentially, mouse-php leverages native PHP hash table lookups to achieve near-instantaneous O(1) route matching.
While mouse-php supports dynamic URI parameters for traditional RESTful endpoints and CRUD views, direct string lookups offer superior performance. To maximize execution speed, mouse-php recommends a lightweight JSON-RPC pattern called mouse RPC. This page details route registration, dynamic parameter syntax, and how to structure high-performance requests using mouse RPC.
Routes are registered as key-value pairs inside flat PHP associative arrays separated into two distinct files:
-
./routes/Api_Routes.php -
./routes/Web_Routes.php
Separating routes at the file level reduces search space overhead before matching even begins and keeps route configurations clean and maintainable.
Note on API Prefixes: All routes defined inside
Api_Routes.phpautomatically have the/apipath segment prepended to them. For example, registering/testinApi_Routes.phpmaps directly to the incoming request path/api/test.
<?php
namespace routes;
class Api_Routes {
public $ROUTES = [
'/test' => ['class' => 'Test_Controller', 'method' => 'get', 'type' => 'GET'],
];
}When Mouse_Core::load_routing() executes, it immediately inspects the first segment of the incoming request URI to classify the request type:
-
API Routes (
/api/*): Targeted for JSON payload delivery. Errors return structured JSON (404 Not Found), and request handling bypasses HTML rendering pipelines. -
Web Routes (
/*): Used for static or server-served assets and fallback handling.
Separating these at the initial URI level prevents API requests from traversing unnecessary static asset routes, keeping evaluation times minimal.
Dynamic URL components are denoted using the colon envelope syntax: :parameter_name:.
When a URL contains dynamic elements, the router extracts the value and injects it into the $request_data['vars'] array before passing control to the middleware and controller layers.
Defined Route: /api/user/:id:/settings
Incoming URI: /api/user/8921/settings
Extracted State:
$request_data['vars']['id'] = "8921";
Inside your controller method, dynamic parameters are accessible directly from the passed $request_data payload:
class User_Controller {
public $REQUEST_DATA;
public $DB;
public function __construct($db, $sqlite, $request_data) {
$this->REQUEST_DATA = $request_data;
$this->DB = $db;
}
public function get_user() {
$user_id = $this->REQUEST_DATA['vars']['id'];
$model = new \models\User_Model();
$data = $model->get_user($this->DB, $user_id);
if($data) {
echo json_encode(["data" => $data]);
}
else {
echo json_encode(['error' => 'User not found']);
}
}
}While dynamic parameters offer convenience for RESTful URIs, they are not the primary recommended way to pass transactional data in mouse-php. Instead, mouse-php encourages structuring API traffic using a JSON-RPC derivative called mouse RPC.
-
Instant Hash Matching (Zero String-Splitting Overhead): The
mouse-phprouting engine always attempts a direct array key match ($ROUTES[$uri]) before falling back to scan for dynamic colon parameters (:var:). Direct matches hit the native PHP hash table in O(1) time without needing to execute string-splitting (explode()) logic. Fixed endpoints combined with mouse RPC payloads execute faster than REST URIs. - Unified Data Pipeline: With mouse RPC, the URI serves a single purpose: routing the request to the correct controller and method. The HTTP request body carries a serialized JSON object containing all required parameters. Controllers do not need to parse data from multiple disparate sources (query strings, path parameters, and body payloads).
-
Optimized for Decoupled Frontends: When serving Single Page Applications (SPAs) or mobile frontends, almost every request carries contextual state (session tokens, client capabilities, or filter criteria). Routing to static endpoints with structured JSON payloads matches the data-marshalling role of
mouse-php.
┌──────────────────────────────────────────────────────────────┐
│ REST vs. MOUSE RPC FLOW │
├──────────────────────────────────────────────────────────────┤
│ REST Style (Slower): │
│ GET /api/user/8921/posts?sort=desc │
│ └─ Requires URI string splitting + query string parsing │
│ │
│ mouse RPC Style (Faster): │
│ POST /api/user/get_posts │
│ └─ Direct O(1) hash lookup + unified JSON body payload │
└──────────────────────────────────────────────────────────────┘
Client Integration: You don't need to manually build mRPC packet signatures or Web Crypto abstractions in your frontend codebase.
coby-jackconsumesmrpc-jsto automatically sign, timestamp, and validate every incoming and outgoing payload. Learn more in Client Ecosystem & Integration.
Most monolithic frameworks evaluate routes by running incoming URIs through a stack of Compiled Regular Expressions (preg_match). As an application grows to hundreds of routes, Regex matching scales linearly O(N) slowing down request evaluation.
mouse-php uses direct associative array lookup:
-
Exact Path Matching: Direct string key lookups (
$ROUTES[$uri]) run in O(1) constant time regardless of whether your app has 5 or 5,000 routes. -
Dynamic Route Parsing: When dynamic colons (
:var:) are present,mouse-phpuses fast string splitting (explode('/', $uri)) to match parameter positions directly against indexed tokens rather than executing heavy regular expression engines.
┌─────────────────────────────────────────────────────────────┐
│ ROUTING TIME COMPLEXITY │
├──────────────────────────────┬──────────────────────────────┤
│ Framework / Strategy │ Lookup Complexity │
├──────────────────────────────┼──────────────────────────────┤
│ Traditional Regex Routers │ O(N) - Linear scan │
│ mouse-php Hash Array Lookup │ O(1) - Direct Hash Lookup │
└──────────────────────────────┴──────────────────────────────┘
Because mouse-php defers database connection initialization until after route confirmation, invalid or malicious requests fail early during the array lookup stage. Unmatched URIs exit instantly with a 404 response, consuming virtually zero CPU or memory and completely avoiding database socket overhead.