Download the PHP package devsrealm/tonics-router-system without Composer
On this page you can find all versions of the php package devsrealm/tonics-router-system. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download devsrealm/tonics-router-system
More information about devsrealm/tonics-router-system
Files in devsrealm/tonics-router-system
Package tonics-router-system
Short Description An Imaginary PHP Router System For Tonics Projects
License Apache-2.0
Informations about the package tonics-router-system
Tonics Router System
A Trie based PHP Router System For Tonics Projects.
This would serve as a base router for tonics web apps, the router is different from most PHP Router in the sense that it doesn't use regex for matching urls, it instead uses a tree data structure where every path is hierarchically organized making it faster for finding both static or dynamic url.
Additionally, I came up with a concept called Node Teleporting which can further enhance and speed up searching dynamic routes, in the best case, dynamic route would be matched directly just like the static routes, and in the worse case, it would teleport a couple of times which is also faster than mere traversing.
You can learn more about the teleporting in the part 2 of how the router works.
Features
- Fast Trie-based routing - Uses a tree data structure instead of regex for faster URL matching
- Node Teleporting - Advanced optimization for dynamic routes
- PSR-7 Support - Full PSR-7 HTTP message interface compatibility
- Backward Compatible - Works with traditional PHP globals or PSR-7 objects
- Request Interceptors - Middleware-like functionality for request processing
- Route Groups - Organize routes hierarchically with shared attributes
- Dependency Injection - Built-in container for automatic dependency resolution
Requirements
- PHP 8.0 and above
- PHP mbstring extension enabled.
Installation
If you don't want to use composer, go-to the release section and download the zip file that has a postfix of composer-no-required e.g tonics-router-system-v1.0.0-composer-no-required.zip
Unzip it and require it like so:
How The Router Works
- A Faster Router System in PHP (Part 1)
- A Faster Router System in PHP (Part 2) (Improvement & Benchmarks)
Documentation
Before you get started, wire up the Router dependencies:
Basic routing
First parameter is the url paths which you want the route to match, and the second parameter could be a closure or a callback function that the route would call once the route matches.
If you want to keep things organized, you can also resolve through a class method, like so:
Request Interceptors
Some call it middleware, requestInterceptor sounds plain and simple to me.
RequestInterceptors can be used to intercept a request before it moves to the next life cycle or to other request interceptors.
For example, if you have an admin url path: /admin, and you want to check if a user is logged in before processing the request, you use the request interceptor. Let's see an example:
in isAuthenticated() class you can have something as such:
We implemented the TonicsRouterRequestInterceptorInterface (it is a must to implement the interface to use the request interceptor) which provides a handle method with the $request object.
Inside the handle method, I am checking if user is not authenticated, and thus redirecting them to their proper destination.
However, if user is authenticated, the interceptor would move to the next life cycle in the route state, the next life cycle could be a new request interceptor or a class method or a callback delegation.
To add more request interceptors, simply do:
Route Required parameters
To match a dynamic url parameter you do:
where you capture the slug from the url, for example, if user visits /posts/blog-post-title, you get access
to blog-post-title.
Alternatively you can do
where `PostsController could look like:
Route Groups
With the route group you could organize route in a tree like fashion, the good thing about this approach is
you can share route attributes, such as route interceptors, parent url paths, etc. across a large number of routes without needing to define those attributes on each individual route.
instead of doing this:
do this:
The end goal is identical to the above one but this is better organized.
You could also nest a group:
Route HTTP Verbs
$route->get(string $url, array|Closure $callback, array $requestInterceptor = [])$route->post(string $url, array|Closure $callback, array $requestInterceptor = [])$route->put(string $url, array|Closure $callback, array $requestInterceptor = [])$route->patch(string $url, array|Closure $callback, array $requestInterceptor = [])$route->delete(string $url, array|Closure $callback, array $requestInterceptor = [])$route->match(array $method, string $url, \Closure|array $callback, array $requestInterceptor = [])
With match, you can match multiple HTTP verbs in one fell swoop.
PSR-7 Support
The Tonics Router System now has full PSR-7 support while maintaining 100% backward compatibility. You can choose to use PSR-7 HTTP message interfaces or continue using the traditional approach.
Why Use PSR-7?
PSR-7 provides standardized HTTP message interfaces that:
- Work seamlessly with modern PHP frameworks and libraries
- Enable better testing with mock request/response objects
- Provide immutable request/response objects for safer code
- Follow PHP-FIG standards for better interoperability
Using PSR-7 Router (Recommended for new projects)
The easiest way to use PSR-7 is with the Psr7Router class:
Important PSR-7 Best Practice: Controllers should return content, not echo it:
If you have legacy code that uses echo, you can use handleWithOutputBuffering() temporarily:
However, refactoring to return values is strongly recommended for proper PSR-7 compliance.
Manual PSR-7 Usage (Advanced)
For more control, you can manually create PSR-7 objects:
Creating Router with Custom Container
Auto-wiring Example
The container can automatically resolve dependencies if they're type-hinted:
Using PSR-7 Request Adapter
You can also use PSR-7 requests with individual components:
Using PSR-7 Response Adapter
For PSR-7 compliant responses:
Backward Compatibility
All existing code continues to work! The traditional approach still works exactly as before:
PSR-7 in Controllers
When using PSR-7, you can type-hint PSR-7 interfaces in your controllers:
Testing with PSR-7
PSR-7 makes testing much easier:
Working with Controllers
Controllers help organize your application logic. Here are practical examples:
Basic Controller Example
Controller with Route Parameters
Controller with Dependency Injection
The router automatically resolves dependencies through the container:
RESTful Controller Example
PSR-7 Controller Example
Complete Example with Container + PSR-7
Here's a full real-world example showing how everything works together:
Request Interceptors (Middleware) Examples
Request Interceptors act as middleware to process requests before they reach your controllers.
Authentication Interceptor
CORS Interceptor
JSON Content-Type Validator
Rate Limiting Interceptor
Logging Interceptor
Multiple Interceptors Example
Best Practices
1. Controller Organization
✅ DO: Keep controllers focused and single-purpose
❌ DON'T: Create god controllers
2. Return Values vs Echo
✅ DO: Return values from controllers (especially for PSR-7)
❌ DON'T: Echo directly in controllers
3. Use Dependency Injection
✅ DO: Inject dependencies via constructor
❌ DON'T: Create dependencies inside methods
4. Request Interceptor Best Practices
✅ DO: Keep interceptors focused on one concern
✅ DO: Chain interceptors for multiple checks
❌ DON'T: Create monolithic interceptors
5. Route Organization
✅ DO: Group related routes
❌ DON'T: Mix unrelated routes
6. Error Handling
✅ DO: Handle errors gracefully
✅ DO: Use proper HTTP status codes
7. Input Validation
✅ DO: Validate input data
8. Use Response Helper (PSR-7)
✅ DO: Use response adapter for clean code
9. Security Best Practices
✅ DO: Sanitize user input
✅ DO: Use HTTPS for sensitive operations
✅ DO: Validate CSRF tokens
All versions of tonics-router-system with dependencies
php Version ^8.0
nyholm/psr7 Version ^1.8
psr/http-message Version ^1.0 || ^2.0
psr/http-factory Version ^1.0