aphp/router

PHP Router, Simple, no-dependencies


Keywords
php, router, Simple, fast, no-dependencies
License
MIT

Documentation

Router

PHP Support PHP Support License Travis

Introduction

aphp/router is a lightweight and simple object oriented PHP Router.

Installation

composer require aphp/router ~1.1.0

Features

  • Supports GET, POST, PUT, DELETE, OPTIONS, PATCH and HEAD request methods.
  • Routing shorthands such as get(), post(), put(), …
  • Dynamic Route Patterns: PCRE-based.
  • Route groups.
  • Supports X-HTTP-Method-Override header.
  • 404 handling.
  • PHP built in server rewrite router.
  • CRUD Api.

Syntax

Intialization

$router = new Router();

$router->set404(function() use ($router) {
  header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
  // ...
});

// ...

$router->run();

Shorthands for single request methods are provided:

$router->get('pattern', function() { /* ... */ });
$router->post('pattern', function() { /* ... */ });
$router->put('pattern', function() { /* ... */ });
$router->delete('pattern', function() { /* ... */ });
$router->options('pattern', function() { /* ... */ });
$router->patch('pattern', function() { /* ... */ });

PCRE-based Route Patterns

  • /movies/(\d+) = One or more digits (0-9)
  • /profile/(\w+) = One or more word characters (a-z 0-9 _)
  • [a-z0-9_-]+ = One or more word characters (a-z 0-9 _) and the dash (-)
  • .*? = Any character (including /), zero or more
  • [^/]+ = Any character but /, one or more
  • {param} = Equivalent (.*?)
  • Router::ANY_URL = Any url , returns current URI in callback function

Note: PHP-regex-cheat-sheet.pdf

Groups

Use $router->group($baseroute, $fn) to group a collection of routes onto a subroute pattern.

$router->group('/movies', function() use ($router) {
  // will result in '/movies/'
  $router->get('/', function() {
    echo 'movies overview';
  });
  // will result in '/movies/id'
  $router->get('/(\d+)', function($id) {
    echo 'movie id ' . htmlentities($id);
  });
});

Cancel routing

In some cases needs to cancel routing, by the application logic.
Use $router->cancel() method to handle this.

$router->set404(function() use ($router) {
  header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found");
  echo '404 Not Found';
});
$router->get('/movies/(\d+)', function($id) use($router) {
  if ($id == 5000) {
    $router->cancel(); // <<
    return;
  }
  echo 'movie id ' . htmlentities($id);
});
$router->run();

If \movies\5000 then 404 page will show.

Any url

In some cases needs a full manual route control

$router->get(Router::ANY_URL, function($url) use($router) {
  if ($url == '/url') {
    // logic
  } else {
    $route->cancel();
  }
});

Case sensitive

By default router works in incasesensitive mode.
To enable case sensitive use code:

$router->useCaseSensitive = true;

$router->get('/caseSensitiveUrl', function() {
  // logic
});

Reset request

By default request values is cached, to reset its use this code:

$router->request->reset();

CRUD Api

Router support CRUD Api

Specification

  • CRUD api used for "create update delete list validate" requests standardization
  • GET and POST requests
  • id passing in GET
  • Used only this requests:
    • GET .../list
    • GET .../new/edit
    • GET .../__id__/edit
    • GET .../__id__/delete
    • GET .../__id__/delete-dialog
    • POST .../new/update
    • POST .../__id__/update
    • POST .../new/validate
    • POST .../__id__/validate
    • POST .../preview

Example

$router = new Router();
$router->crudapi('/itemname', function($crud, $id){
  if ($crud == Router::CRUD_LIST) {
    // itemname/list
    // logic
  }
  if ($crud == Router::CRUD_EDIT) {
    // itemname/new/edit
    // itemname/__id__/edit
    // logic
  }
  // ..
});

CRUD Api Interface

CRUDApiInterface using for objects, router automatically call methods.

class Controller implements CRUDApiInterface {
  public $crud_method;
  public $crud_id;

  function rlist() { /* ... */ }

  function edit($id) { /* ... */ }

  function delete($id) { /* ... */ }

  function deleteDialog($id) { /* ... */ }

  function update($id) { /* ... */ }

  function validate($id) { /* ... */ }

  function preview() { /* ... */ }
}

// call by Closure
$router->crudapiCallInterface('/itemname', function() { return new Controller(); });
// OR call by className
$router->crudapiCallInterface('/itemname', Controller::class);
// OR call by className string
$router->crudapiCallInterface('/itemname', 'Controller');

Test running

  • install phpunit, composer, php if not installed
  • run composer install at package dir
  • run tests/startBuildInServer.bat
  • run tests/startServer.bat
  • run tests/startTest.bat

On linux use *.sh files like *.bat files

🔵 Useful links

More features

For more features:

  • Read source code and examples
  • Practice with Router in real code