PHP Classes

How Use a PHP Router Library to Process HTTP Requests with Callback Functions Using the Package Lou Router: Route HTTP requests using callback functions

Recommend this page to a friend!
     
  Info   Example   View files Files   Install with Composer Install with Composer   Download Download   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2025-04-07 (11 days ago) RSS 2.0 feedNot yet rated by the usersTotal: Not yet counted Not yet ranked
Version License PHP version Categories
lou-router 1.0.0GNU General Publi...5HTTP, PHP 5, Design Patterns
Description 

Author

This package can route HTTP requests using callback functions.

It provides a class that can register routes and associate request URLs with callback functions.

The class can process an HTTP request to check the request URL and call a registered callback function if it matches one of the routes that was previously associated.

This project implements a simple PHP router for basic URL routing within a web application.

Currently, it provides:

- Simple Route Definition: Easily define routes using the `addRoute()` method.

- Callback Functions: Associate each route with a callback function that handles the request.

- 404 Error Handling: Gracefully handles requests to undefined routes with a custom 404 error page.

- Clean URL Handling: Removes leading and trailing slashes from URLs for consistent matching.

- Content Injection: The router injects the content in the index.php file.

Picture of António Lourenço
  Performance   Level  
Name: António Lourenço <contact>
Classes: 8 packages by
Country: Portugal Portugal

Instructions

Defining Routes (routes.php)

  1. Include Router.php:
    require_once 'Router.php';
    
  2. Create a Router Instance:
    $router = new Router();
    
  3. Add Routes: Use the `addRoute()` method to define routes and their callbacks:
    $router->addRoute('/', function() {
        $content = "This page is index!";
    });
    
    $router->addRoute('home', function() {
        require_once 'home.php';
    });
    
    $router->addRoute('about', function() {
        require_once 'about.php';
    });
    
    $router->addRoute('contact', function() {
        require_once 'contact.php';
    });
    

    * The first argument to `addRoute()` is the URL path (e.g., `/`, `home`, `about`). * The second argument is a callback function that will be executed when the route is matched. * The callback function can set the `$content` variable or include a php file.

Running the Router (index.php)

  1. Include router.php and routes.php:
    require_once 'router.php';
    require_once 'routes.php';
    
  2. Run the Router:
    $router->run();
    
    This will process the current URL and execute the appropriate callback.
  3. Content injection:
    <div id="content">
    		<?php
    			if (!isset($content)) {
    				$content = '';
    			} 
            echo $content;
        ?>
    </div>
    
    This code will inject the content of the `$content` variable in the page.

Creating Content Files (home.php, about.php, contact.php)

These files contain the content that will be displayed for their respective routes. Example (contact.php):

     $content = 'This page is CONTACT';

Example

<?php
   
// add the Router class
   
require_once 'Router.php';

   
// Create a Router instance
   
$router = new Router();

   
// Add routes
   
$router->addRoute('/', function() {
        global
$content;
       
$content = "This page is index!";
        require_once
'index.php';
    });
   
   
$router->addRoute('home', function() {
        global
$content;
        require_once
'home.php';
    });

   
$router->addRoute('about', function() {
        global
$content;
        require_once
'about.php';
    });

   
$router->addRoute('contact', function() {
        global
$content;
        require_once
'contact.php';
    });


Details

This project implements a simple PHP router for basic URL routing within a web application. It allows developers to define routes (URLs) and associate them with specific actions or content, represented by callback functions or included PHP files. The router handles clean URLs, provides a basic 404 error page, and injects dynamic content into a main layout. It's designed for small to medium-sized projects where a lightweight routing solution is needed. # Simple PHP Router This is a basic PHP router designed to handle simple URL routing within a web application. It allows you to define routes and associate them with specific actions or content. ## Overview This router provides a clean and straightforward way to map URLs to specific PHP files or functions. It's ideal for small to medium-sized projects where a full-fledged framework might be overkill. ## Features * **Simple Route Definition:** Easily define routes using the `addRoute()` method. * **Callback Functions:** Associate each route with a callback function that handles the request. * **404 Error Handling:** Gracefully handles requests to undefined routes with a custom 404 error page. * **Clean URL Handling:** Removes leading and trailing slashes from URLs for consistent matching. * **Content Injection:** The router injects the content in the index.php file. ## File Structure * **`index.php`:** The main entry point of the application. It includes the router and defines the basic HTML structure. * **`router.php`:** Contains the `Router` class, which handles route management and execution. * **`routes.php`:** Defines the application's routes and their associated callbacks. * **`home.php`:** Example content file for the `/home` route. * **`about.php`:** Example content file for the `/about` route. * **`contact.php`:** Example content file for the `/contact` route. ## Usage ### Defining Routes (`routes.php`) 1. **Include `Router.php`:** ```php require_once 'Router.php'; ``` 2. **Create a Router Instance:** ```php $router = new Router(); ``` 3. **Add Routes:** Use the `addRoute()` method to define routes and their callbacks: ```php $router->addRoute('/', function() { $content = "This page is index!"; }); $router->addRoute('home', function() { require_once 'home.php'; }); $router->addRoute('about', function() { require_once 'about.php'; }); $router->addRoute('contact', function() { require_once 'contact.php'; }); ``` * The first argument to `addRoute()` is the URL path (e.g., `/`, `home`, `about`). * The second argument is a callback function that will be executed when the route is matched. * The callback function can set the `$content` variable or include a php file. ### Running the Router (`index.php`) 1. **Include `router.php` and `routes.php`:** ```php require_once 'router.php'; require_once 'routes.php'; ``` 2. **Run the Router:** ```php $router->run(); ``` This will process the current URL and execute the appropriate callback. 3. **Content injection:** ```php <div id="content"> <?php if (!isset($content)) { $content = ''; } echo $content; ?> </div> ``` This code will inject the content of the `$content` variable in the page. ### Creating Content Files (`home.php`, `about.php`, `contact.php`) These files contain the content that will be displayed for their respective routes. Example (`contact.php`): ```php $content = 'This page is CONTACT'; ``` ## Limitations *Basic Functionality: This is a very basic router and does not include advanced features like route parameters, middleware, or complex routing patterns. *No HTTP Method Handling: It doesn't differentiate between HTTP methods (GET, POST, etc.). *No error handling: The code does not have a good error handling. # License This project is open-source and available under the MIT License.

  Files folder image Files (10)  
File Role Description
Accessible without login Plain text file .htaccess Conf. conf
Accessible without login Plain text file 404.php Example web page
Accessible without login Plain text file about.php Example web page
Accessible without login Plain text file contact.php Example web page
Accessible without login Plain text file home.php Example web page
Accessible without login Plain text file index.php Example Example
Accessible without login Plain text file readme Doc. documentation
Plain text file router.php Class Simple PHP router for basic URL routing
Accessible without login Plain text file routes.php Example Route configuration example
Accessible without login Plain text file LICENSE Lic. License text

The PHP Classes site has supported package installation using the Composer tool since 2013, as you may verify by reading this instructions page.
Install with Composer Install with Composer
 Version Control Unique User Downloads  
 10%
Total:0
This week:0