08/12
2014
Wallogit.com
2017 © Pedro Peláez
router with routes groups & before-after actions
Composer install:, (*1)
composer require sw04/route-me
Initialize:, (*2)
$router = \Router\Singleton::getInstance();
Simple route for GET and POST methods with required integer and string param:, (*3)
$router->get('/show/{[0-9]+}'); //sample: GET /show/1024
$router->post('/show/{[a-z]+}'); //sample: POST /show/sample
Simple route with not required param:, (*4)
$router->get('/show/!{[0-9]+}'); //sample: GET /show or /show/1024
Simple route with defined controller & method:, (*5)
$router
->setController('index')
->setMethod('index')
->get('/')
->clear();
Simple group routes(set prefix "/admin") and add actions before route match:, (*6)
function isAuth() {
//check auth & return true or false
return true;
}
function isAdmin() {
//check role is admin or not & return true or false
return false;
}
$router
->setPrefix('/admin')
->setAction('before', 'isAuth')
->setAction('before', 'isAdmin')
->get('/dashboard')
->clear();
Simple set prefix(namespace) for all classes:, (*7)
$router->setNamespace('\\Application\\Project\\');
Match routes:, (*8)
try {
$result = $router->match(getenv('REQUEST_URI'));
if (is_array($result)) { //convert to json if is array
$result = json_encode($result);
}
echo $result; //echo result of match
} catch(\Router\RouterException $e) {
echo $e->getMessage().' code is '.$e->getCode();
}
All routes set next requirements for routes:, (*9)
method - GET, POST, ANY prefix - for route url url - to route actions - before & after route match defineClass - define controller defineMethod - define method defineParams - define params
For clear all this requirements use:, (*10)
$routes->clear();