Routing
The Ecommerce\Core\Route class provides a fluent interface for defining REST API routes.
Introduction
The Route API serves as the central point for defining your application's HTTP endpoints. It provides a static, fluent interface for registering routes that respond to standard HTTP verbs, attaching middleware for request filtering, and grouping routes for better organization.
By ensuring a consistent routing structure, the Route API helps maintain a clean separation between your application's entry points and its logic.
HTTP Methods
The Route class provides static methods for registering routes for all standard HTTP verbs.
Register GET Route
Register a route that responds to HTTP GET requests.
Description:
The get() method registers a route that listens for GET requests at the specified endpoint. It maps the request to a controller method. This is typically used for retrieving resources.
Method Signature:
public static function get(string $endpoint, array $action): Route
Parameters:
$endpoint- The URI pattern for the route (e.g.,/products,/orders/{id})$action- An array containing the controller class name and the method name to call
Examples:
// Basic route to list all products
Route::get('/products', [ProductController::class, 'index']);
// Route with a parameter to show a specific product
Route::get('/products/{id}', [ProductController::class, 'show']);
// Route to get a specific order by UUID
Route::get('/orders/{uuid}', [OrderController::class, 'show']);
// Route to search for customers
Route::get('/customers/search', [CustomerController::class, 'search']);
// Route to get reviews for a specific product
Route::get('/products/{id}/reviews', [ReviewController::class, 'index']);
Register POST Route
Register a route that responds to HTTP POST requests.
Description:
The post() method registers a route that listens for POST requests. This is typically used for creating new resources or performing actions that change the server state.
Method Signature:
public static function post(string $endpoint, array $action): Route
Parameters:
$endpoint- The URI pattern for the route$action- An array containing the controller class name and the method name
Examples:
// Create a new product
Route::post('/products', [ProductController::class, 'store']);
// Create a new order
Route::post('/orders', [OrderController::class, 'store']);
// Add a customer
Route::post('/customers', [CustomerController::class, 'create']);
// process a refund
Route::post('/orders/{id}/refund', [OrderController::class, 'refund']);
Register PUT Route
Register a route that responds to HTTP PUT requests.
Description:
The put() method registers a route that listens for PUT requests. This is typically used for full updates of existing resources.
Method Signature:
public static function put(string $endpoint, array $action): Route
Parameters:
$endpoint- The URI pattern for the route$action- An array containing the controller class name and the method name
Examples:
// Update a product
Route::put('/products/{id}', [ProductController::class, 'update']);
// Update an order status
Route::put('/orders/{id}/status', [OrderController::class, 'updateStatus']);
// Update customer profile
Route::put('/customers/{id}', [CustomerController::class, 'update']);
Register PATCH Route
Register a route that responds to HTTP PATCH requests.
Description:
The patch() method registers a route that listens for PATCH requests. This is typically used for partial updates of existing resources.
Method Signature:
public static function patch(string $endpoint, array $action): Route
Parameters:
$endpoint- The URI pattern for the route$action- An array containing the controller class name and the method name
Examples:
// Partially update a product (e.g., just the stock)
Route::patch('/products/{id}', [ProductController::class, 'update']);
// Update a specific field of an order
Route::patch('/orders/{id}/address', [OrderController::class, 'updateAddress']);
// Enable/Disable a user
Route::patch('/users/{id}/status', [UserController::class, 'toggleStatus']);
Register DELETE Route
Register a route that responds to HTTP DELETE requests.
Description:
The delete() method registers a route that listens for DELETE requests. This is used for deleting resources.
Method Signature:
public static function delete(string $endpoint, array $action): Route
Parameters:
$endpoint- The URI pattern for the route$action- An array containing the controller class name and the method name
Examples:
// Delete a product
Route::delete('/products/{id}', [ProductController::class, 'destroy']);
// Delete an order
Route::delete('/orders/{id}', [OrderController::class, 'destroy']);
// Delete a customer account
Route::delete('/customers/{id}', [CustomerController::class, 'delete']);
Route Configuration
Methods to configure the registered route, such as adding middleware or defining parameter patterns.
Attach Middleware
Attach one or more middleware to the route.
Description:
The middleware() method attaches middleware classes to the route. Middleware can intercept requests before they reach the controller to perform authentication, validation, or other checks.
Method Signature:
public function middleware(string|array $middleware): Route
Parameters:
$middleware- A single middleware class name or an array of middleware class names
Examples:
// Attach a single middleware
Route::get('/admin/dashboard', [AdminController::class, 'index'])
->middleware(AuthMiddleware::class);
// Attach multiple middleware
Route::post('/orders', [OrderController::class, 'store'])
->middleware([AuthMiddleware::class, ValidateOrderMiddleware::class]);
// Protect customer routes
Route::put('/customers/{id}', [CustomerController::class, 'update'])
->middleware([AuthMiddleware::class, CustomerAccessMiddleware::class]);
Define Parameter Patterns
Set regex constraints for route parameters.
Description:
The where() method allows you to define regular expression constraints for route parameters. If the parameter value in the request URL does not match the pattern, the route will not match.
Method Signature:
public function where(string $name, string $regex): Route
Parameters:
$name- The name of the route parameter (without curly braces)$regex- The regular expression pattern to match
Examples:
// Ensure 'id' is numeric
Route::get('/products/{id}', [ProductController::class, 'show'])
->where('id', '[0-9]+');
// Ensure 'slug' contains only lowercase letters, numbers, and dashes
Route::get('/blog/{slug}', [BlogController::class, 'show'])
->where('slug', '[a-z0-9-]+');
// Complex constraints for multiple parameters
Route::get('/orders/{year}/{month}', [OrderController::class, 'archive'])
->where('year', '[0-9]{4}')
->where('month', '[0-9]{2}');
Route Groups
Group routes to share common configuration.
Create Route Group
Register a group of routes with shared options like prefix and middleware.
Description:
The group() method allows you to group multiple routes together and apply shared attributes such as URL prefixes and middleware. This helps in organizing routes and reducing code duplication.
Method Signature:
public static function group(array $options, Closure $closure): void
Parameters:
$options- An array of options (prefix,middleware)$closure- A closure that defines the routes within the group
Examples:
// Group routes under '/admin' prefix with 'AuthMiddleware'
Route::group(['prefix' => 'admin', 'middleware' => AuthMiddleware::class], function () {
// Generates: GET /admin/dashboard
Route::get('/dashboard', [AdminController::class, 'dashboard']);
// Generates: GET /admin/products
Route::get('/products', [AdminController::class, 'products']);
// Generates: POST /admin/settings
Route::post('/settings', [AdminController::class, 'saveSettings']);
});
// Nested groups are also supported (conceptually, depends on implementation details but common in frameworks)
Route::group(['prefix' => 'api'], function () {
Route::group(['prefix' => 'v1'], function () {
Route::get('/status', [SystemController::class, 'status']);
});
});
Static Methods
Utility methods for global route configuration and retrieval.
Set Namespace
Set the global API namespace for all routes.
Description:
The set_namespace() method sets the base namespace for the REST API. This is typically called in your application service provider or initialization file. All routes registered subsequently will be under this namespace.
Method Signature:
public static function set_namespace(string $namespace): void
Parameters:
$namespace- The namespace string (e.g., 'droip/v1')
Examples:
// Set the namespace to 'my-shop/api'
Route::set_namespace('my-shop/api');
// Now, Route::get('/products', ...) corresponds to /my-shop/api/products
Get All Routes
Retrieve the list of all registered routes.
Description:
The get_routes() method returns an array of all Route instances that have been registered. This can be useful for debugging or generating API documentation.
Method Signature:
public static function get_routes(): array
Parameters:
- None
Examples:
$routes = Route::get_routes();
foreach ($routes as $route) {
// Inspect route properties
// echo $route->method . ' ' . $route->endpoint;
}