PHP Classes

Simple PHP Router: Route HTTP requests to 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    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 79 All time: 10,129 This week: 61Up
Version License PHP version Categories
simpleroute 1.0.0MIT/X Consortium ...8HTTP, Design Patterns, PHP 8
Description 

Author

This package can route HTTP requests to callback functions.

It can register the URL paths, HTTP methods, and associated callback functions.

The package can also process the current HTTP request and invoke the callback function matching the registered URL paths and HTTP methods.

Picture of Mateo
  Performance   Level  
Name: Mateo <contact>
Classes: 23 packages by
Country: Peru Peru
Innovation award
Innovation award
Nominee: 10x

Winner: 3x

Example

<?php

use Mateodioev\HttpRouter\exceptions\{HttpNotFoundException, RequestException};
use
Mateodioev\HttpRouter\{Request, Response, Router};

require
__DIR__ . '/vendor/autoload.php';

$conf = new \Mateodioev\StringVars\Config;
$conf->addFormat('uuid', '([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})');

$router = new Router($conf);

$router->get('/', function () {
    return
Response::text('Hello world!')
        ->
setHeader('X-message', 'Method GET');
});

$router->post('/', function () {
    return
Response::json(['message' => 'Hello World!'])
        ->
setHeader('X-message', 'Method POST');
});

// Conditional params
$router->get('/page/{all:id}?', function (Request $r) {
    return
Response::text($r->param('id') ?? 'default page');
});

// Mandatory params
$router->get('/usr/{name}', function (Request $r) {
    return
Response::text('Hello ' . $r->param('name'));
});

// Using custom format
$router->get('/user/{uuid:id}', function (Request $r) {
    return
Response::text('Hello user id ' . $r->param('id'));
});
// try: /usr/123e4567-e89b-12d3-a456-426655440000

try {
   
$router->run();
} catch (
HttpNotFoundException $e) {
   
$router->send(Response::text($e->getMessage() ?? 'Not found')->setStatus(404));
} catch (
RequestException $e) {
   
$router->send(Response::text($e->getMessage() ?? 'Server error')->setStatus(500));
}


Details

Simple HTTP router

> :warning: This project was made for educational purposes only. It is not intended to be used in production environments.

Usage

use Mateodioev\HttpRouter\exceptions\{HttpNotFoundException, RequestException};
use Mateodioev\HttpRouter\{Request, Response, Router};

$router = new Router();

// Register your endpoints here
$router->get('/', function (Request $r) {
    return Response::text('Hello world!');
});

$router->run();

Methods

You can use the Router::get, Router::post, Router::put, Router::patch and Router::delete methods to register your endpoints.

$router->myHttpMethod($uri, $callback);
  • `$uri` is the path of the endpoint.
  • `$callback` is the function that will be executed when the endpoint is requested. Each callback (action) must return an instance of the Mateodioev\HttpRouter\Response class or an InvalidReturnException will be thrown.

Static files

You can map all static files in a directory with the static method.

$router->static($baseUri, $path, $methods);
// Default methods are GET

Example:

tree
.
??? index.php
??? styles.css

1 directory, 2 files

$router->static('/docs', 'public/');

Now you can reach this uris

  • /docs/index.php
  • /docs/styles.css

Handling all HTTP methods

You can use the Router::all method to handle all HTTP methods with one callback.

$router->all($uri, $callback);

Path parameters

You can use path parameters in your endpoints. Path parameters are defined by a bracket followed by the name of the parameter. > /users/{id}

$router->get('/page/{name}', function (Request $r) {
    return Response::text('Welcome to ' . $r->param('name'));
});

Note: You can make a parameter optional by adding a question mark after the name of the parameter. > /users/{id}?

$router->get('/page/{name}?', function (Request $r) {
    $pageName = $r->param('name') ?? 'home'; // If the parameter is not present, the method return null
    return Response::text('Welcome to ' . $pageName);
});

Request data

You can get all data from the request with the following methods:

  • `Request::method()` returns the HTTP method of the request.
  • `Request::uri()` returns the URI of the request.
  • `Request::uri()` returns the URL of the request.
  • `Request::param($name, $default = null)` returns the value of the parameter with the name `$name` or null if the parameter is not present.
  • `Request::params()` return al the request URI parameters.
  • `Request::headers()` returns an array with all the headers of the request.
  • `Request::body()` returns the body of the request (from php://input).
  • `Request::data()` returns an array with all the data of the request. Use this when Content-Type is _application/x-www-form-urlencoded_ or _multipart/form-data_.
  • `Request::files()` returns an array with all the files of the request.
  • `Request::query()` returns an array with all the query parameters from the uri.

TODO list: - [ ] Add support for middlewares. - [ ] Add support for custom error handlers.


  Files folder image Files (16)  
File Role Description
Files folder imagesrc (6 files, 2 directories)
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file index.php Example Example script
Accessible without login Plain text file readme.md Doc. Documentation

  Files folder image Files (16)  /  src  
File Role Description
Files folder imageexceptions (4 files)
Files folder imageServer (3 files)
  Plain text file Container.php Class Class source
  Accessible without login Plain text file HttpMethods.php Aux. Auxiliary script
  Plain text file Request.php Class Class source
  Plain text file Response.php Class Class source
  Plain text file Route.php Class Class source
  Plain text file Router.php Class Class source

  Files folder image Files (16)  /  src  /  exceptions  
File Role Description
  Plain text file baseException.php Class Class source
  Plain text file HttpNotFoundException.php Class Class source
  Plain text file InvalidReturnException.php Class Class source
  Plain text file RequestException.php Class Class source

  Files folder image Files (16)  /  src  /  Server  
File Role Description
  Plain text file FakeServer.php Class Class source
  Plain text file NativeServer.php Class Class source
  Plain text file Server.php Class Class source

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 Download Rankings  
 100%
Total:79
This week:0
All time:10,129
This week:61Up