The RF PHP Routing Library provides a flexible and easy-to-use routing system for PHP applications. It supports registering routes from separate files, setting maintenance and 404 page handlers, and defining routes with various HTTP methods. Additionally, it supports route grouping for organizing routes under a common prefix.
-
Install via Composer
Make sure you have Composer installed. Run the following command to add the RF PHP Routing Library to your project:
composer require refkinscallv/router
-
Autoload Dependencies
Ensure that your project’s
vendor/autoload.php
is required in your application entry point.require 'vendor/autoload.php';
Before using the routing methods, you need to import the Route
class from the RF\Router
namespace. This is done with the use
statement:
use RF\Router\Route;
This line of code allows you to use the Route
class methods without needing to write the full namespace each time.
You can register routes from different files using the Route::register
method:
Route::register([
'example/route/other'
]);
Define a maintenance page handler:
Route::setMaintenance(function() {
echo "Maintenance Page";
});
// OR
require 'example/page/maintenance.php';
Route::setMaintenance([RF\Page\Maintenance::class, 'index']);
Define a 404 page handler:
Route::set404(function() {
echo "Page Not Found";
});
// OR
require 'example/page/page404.php';
Route::set404([RF\Page\Page404::class, 'index']);
Define routes with different HTTP methods:
Route::get('', function() {
echo "Default Page";
});
// OR
require 'example/page/default.php';
Route::get('', [RF\Page\DefaultPage::class, 'index']);
Route::set
- General method for setting routes (default is GET)Route::get
- GET requestRoute::post
- POST requestRoute::put
- PUT requestRoute::delete
- DELETE requestRoute::patch
- PATCH requestRoute::options
- OPTIONS request
Define routes with optional or required parameters. Optional parameters are denoted with a ?
in the route pattern, indicating that the parameter is not required and can be omitted in the URL.
Define a route with an optional parameter:
Route::get('/param/{id?}', function($id) {
echo 'Add param: ' . ($id ? $id : 'No parameter provided');
});
-
With Parameter:
URL:
/param/123
Output:Add param: 123
-
Without Parameter:
URL:
/param
Output:Add param: No parameter provided
Group routes under a common prefix:
Route::group(['prefix' => '/parent/path'], function() {
Route::get("", function() {
echo "Default Page for /parent/path";
});
Route::get("/child", function() {
echo "Path /child page of /parent/path";
});
});
Finally, execute the router to handle incoming requests:
Route::run();
If you would like to contribute to the development of this library, please submit a pull request or open an issue on GitHub.
This library is licensed under the MIT License. See the LICENSE file for more details.