Routing System
Table of Contents
Introduction
Router Library Overview
Architecture
Route Definition
HTTP Methods
URL Parameters
Route Organization
Advanced Features
Best Practices
Common Patterns
Troubleshooting
Introduction
PHPTRAVELS v10 uses a lightweight, fast, and flexible routing system powered by the qaxim/php-router library. This regex-based router provides clean URL structures, pattern matching, and efficient request handling while maintaining simplicity and performance.
What is Routing?
Routing is the mechanism that maps incoming HTTP requests (URLs) to specific code handlers (functions or controllers). Instead of creating separate PHP files for every page, the router directs all requests through a single entry point and executes the appropriate code based on the URL pattern.
Traditional Approach (Without Router):
Modern Routing Approach:
Benefits of Modern Routing
Clean URLs
SEO-friendly URLs without .php extensions
Readable and memorable paths
Professional appearance
Centralized Control
All routes defined in one location
Easy to maintain and update
Clear application structure
Dynamic Parameters
Extract values from URL paths
Flexible pattern matching
RESTful API support
Security
Single entry point for all requests
Consistent authentication checks
Centralized error handling
Performance
Efficient pattern matching
No filesystem lookups for every request
Optimized for speed
Router Library Overview
About qaxim/php-router
Official Package: https://packagist.org/packages/qaxim/php-router
Key Characteristics:
Lightweight (~300 lines of code)
Zero dependencies (only requires PHP >=5.3.0)
Regex-based pattern matching
RESTful HTTP method support
Closure/callback support
Namespace support for controllers
Service injection capability
Route grouping with prefixes
Installation:
Core Features
1. Regex Pattern Matching Routes support full regular expression patterns for flexible URL matching:
2. HTTP Method Support Full support for all standard HTTP methods:
GET (retrieve data)
POST (create/submit data)
PUT (update existing data)
DELETE (remove data)
PATCH (partial update)
HEAD (headers only)
OPTIONS (CORS preflight)
TRACE (debugging)
CONNECT (proxy tunneling)
3. Closure Handlers Routes can use anonymous functions (closures) for quick implementations:
4. Controller Support Routes can reference controller classes and methods:
5. Service Injection Share services (like database) across all routes:
Architecture
Application Flow
File Structure
.htaccess Configuration
Location: /v10/.htaccess
What it does:
Enables Apache mod_rewrite module
Checks if requested file exists (images, CSS, JS) - serves directly
If file doesn't exist, sends request to index.php
Preserves query strings (QSA)
Stops processing after match (L)
Route Definition
Router Initialization
Location: index.php
Error Handler Parameters:
$method- HTTP method (GET, POST, etc.)$path- Requested URL path$statusCode- HTTP status code (404 for not found)
Basic Route Syntax
Simple GET Route:
Route with Database Access:
Route Handler Structure
Typical Route Pattern in PHPTRAVELS:
Components Explained:
use ($SECURE, $db)
Imports variables from parent scope into closure
$SECURE- Security flag to prevent direct file access$db- Medoo database instance
META DATA
$title- Page title for<title>tag$description- Meta description for SEO$header/$footer- Boolean flags to control layout
View Files
header.php - HTML head, navigation, header
page.php - Main content for the route
footer.php - Footer content, scripts, closing tags
HTTP Methods
GET Method
Used for retrieving data and displaying pages.
Homepage:
User Dashboard:
Flights Module Home:
POST Method
Used for form submissions and data creation.
Login Form Processing:
Signup Form Processing:
PUT Method
Used for updating existing resources (typically for APIs).
DELETE Method
Used for removing resources (typically for APIs).
Handling Multiple Methods
Same Route, Different Methods:
Universal Handler:
URL Parameters
Dynamic Route Parameters
Routes can capture dynamic values from the URL using regular expressions.
Basic Parameter Extraction
User Profile by ID:
Blog Post by Slug:
Multiple Parameters
Flight Search Route:
Complex Flight Route with Multiple Parameters:
Regex Patterns Reference
([0-9]+)
One or more digits
123, 4567
([a-z]+)
One or more lowercase letters
hello, world
([A-Z]{3})
Exactly 3 uppercase letters
NYC, LAX
([a-z0-9-]+)
Letters, numbers, hyphens
my-post-123
([^/]+)
Anything except forward slash
any-text-here
(.*)
Anything (greedy)
captures/everything/remaining
(oneway|roundtrip)
Either "oneway" or "roundtrip"
oneway
([0-9]{4}-[0-9]{2}-[0-9]{2})
Date format YYYY-MM-DD
2024-12-25
Parameter Validation
Always validate captured parameters:
Route Organization
Modular Structure
PHPTRAVELS v10 organizes routes into logical modules for maintainability and scalability.
Master Routes Loader
Location: app/routes/_routes.php
Benefits of This Structure:
Separation of Concerns: Each file handles related routes
Easy Maintenance: Find routes quickly by feature/module
Team Collaboration: Multiple developers can work on different route files
Lazy Loading: Only load needed routes (can be optimized)
Clear Hierarchy: Understand app structure at a glance
Creating a New Route Module
Step 1: Create Route File
Location: app/routes/bookings/history.php
Step 2: Register in _routes.php
Step 3: Create View File
Location: app/views/bookings/history.php
Route File Naming Conventions
Descriptive Names:
users/login.php- User login routesflights/booking.php- Flight booking routesadmin/dashboardRoutes.php- Admin dashboard routes
Plural for Collections:
bookings/list.php- List all bookingsusers/management.php- User management
Suffix for Related Routes:
settingsRoutes.php- Multiple settings-related routesajaxRoutes.php- AJAX endpoint routes
Advanced Features
Route Grouping with Prefixes
Group related routes under a common URL prefix using mount().
Admin Routes Example:
Benefits:
DRY (Don't Repeat Yourself) - Write prefix once
Easy URL restructuring
Logical grouping
Cleaner code
Nested Mounting:
Service Injection
Share services (like database, logger, cache) across all routes.
Setting Service:
Using Service in Routes:
Note: PHPTRAVELS currently uses use ($db) closure syntax instead of service injection, but both approaches are supported.
Custom 404 Handling
Customize error pages based on different scenarios.
Basic 404 Handler:
Advanced 404 with Logging:
Middleware Pattern
Implement middleware-like functionality using helper functions.
Authentication Middleware:
Usage in Routes:
Best Practices
1. Security
Always Validate Input:
CSRF Protection:
SQL Injection Prevention:
2. Performance
Cache Route Results:
Minimize Database Queries:
3. Code Organization
Keep Routes Thin:
Use Constants:
4. Error Handling
Always Handle Errors:
Graceful Degradation:
5. RESTful Design
Follow REST Conventions:
Common Patterns
Pattern 1: Authentication Check
Pattern 2: AJAX JSON Response
Pattern 3: Form Processing with Validation
Pattern 4: Pagination
Pattern 5: File Upload Handling
Troubleshooting
Common Issues
Problem 1: 404 on All Routes
Symptoms:
Homepage works, but all other routes return 404
Apache shows "Not Found" error
Solution:
Check .htaccess file exists in root
Verify mod_rewrite is enabled:
Ensure .htaccess is being read (check Apache config)
Verify .htaccess content:
Problem 2: Route Not Matching
Symptoms:
Route is defined but returns 404
Other routes work fine
Solution:
Check route pattern regex:
Test regex pattern:
Check route order (specific routes before general ones)
Verify route file is included in _routes.php
Problem 3: Parameters Not Captured
Symptoms:
Route matches but parameters are wrong/empty
Solution:
Check regex capturing groups use parentheses:
Verify parameter order matches pattern:
Problem 4: POST Data Not Received
Symptoms:
POST route works but $_POST is empty
Solution:
Check form Content-Type:
For JSON requests, read from input stream:
Problem 5: Infinite Redirect Loop
Symptoms:
Browser shows "Too many redirects" error
Solution:
Debugging Tools
1. Route Inspection:
2. Enable Error Reporting:
3. Log Route Matches:
Summary
The PHPTRAVELS v10 routing system provides:
Lightweight & Fast
Minimal overhead with regex-based matching
Direct callback execution
No heavy framework dependencies
Flexible & Powerful
Full regex support for complex patterns
Multiple parameter extraction
All HTTP methods supported
Well-Organized
Modular route file structure
Logical grouping by feature/module
Easy to maintain and extend
Secure
Single entry point for all requests
Consistent authentication checks
CSRF protection support
Developer-Friendly
Clear, readable syntax
Closure and controller support
Comprehensive error handling
RESTful
Supports REST conventions
Clean URL structures
API-ready architecture
Production-Ready
Handles complex real-world routing needs
Proven in PHPTRAVELS booking platform
Scalable for large applications
The qaxim/php-router library combined with PHPTRAVELS' organized structure creates a robust, maintainable routing system suitable for complex travel booking applications with multiple modules, authentication requirements, and API endpoints.
Last updated