txiki/router

Simple router for PHP

1.0.1 2015-02-26 16:44 UTC

This package is not auto-updated.

Last update: 2024-04-13 15:39:18 UTC


README

Simple router for PHP

Author Latest Version Packagist Version

Software License Build Status Scrutinizer Code Quality Code Coverage

Install

Via Composer

$ composer require txiki/router

Requirements

The following versions of PHP are supported by this version.

  • PHP 5.4
  • PHP 5.5
  • PHP 5.6
  • HHVM

Documentation

Simple example:

// load composer autoload
require '../vendor/autoload.php';

use Txiki\Router\Route;

$r = new Route();

// add GET route
$r->get('/home', function(){
    return "GET Hello world!";
});

//tell router what you want to process, the route and the http method
$route = $r->exec( '/home', 'get');

if($route!==false){
	// example process response
	echo $route->response;
}else{
	// example response 404
	echo '404';
}

Add more routes:

// add POST route
$r->post('/home', function(){
    return "POST Hello world!";
});

// add DELETE route
$r->delete('/home', function(){
    return "DELETE Hello world!";
});

// add PUT route
$r->put('/home', function(){
    return "PUT Hello world!";
});

Wildcard and custom routes:

// add route to any http method
$r->any('/home', function(){
    return "Hello world! respond to any http method";
});

// custom http methods for one route
$r->add('/home', function(){
    return "Hello world! respond to custom http methods";
}, 'get|post');

Manage custom url params:

$r->any('/test-{id}/{name}/{n}', function($id, $name , $n){
    return 'Test: ' . $id .' '.$name.' '.$n;
})->params([
		// add your own regular expression to param or
		// 'use Txiki\Router\RouteRegex'
		'id' => RouteRegex::INT,
		'name' => RouteRegex::ALPHA,
		'n' => RouteRegex::INT
	]
);

Use class/method as callback:

class myClass{
    public function method1( $id, $name){
        return 'Hello world ' .$id . ' '. $name;
    }
}

$r->get('/user/{id}/{name}', 'myClass::method1');

Helper methods:

// get all established routes
$table = $r->table();

// get all routes for '/home'
$map = $r->getRouteMap('/home');

// get only POST route for '/home'
$map = $r->getRouteMap('/home', 'post');

Testing

$ vendor/bin/phpunit

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.