1. Go to this page and download the library: Download mattferris/http-routing library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mattferris / http-routing example snippets
use MattFerris\Http\Routing\Dispatcher;
$dispatcher = new Dispatcher($request);
// get a response
$response = $dispatcher->dispatch($request);
// handle requests for GET /foo with a closure
$dispatcher->get('/foo', function () {
return $response;
});
// handle requests for POST /foo with the fooAction() method on the Controller class
$dispatcher->post('/foo', 'Controller::fooAction');
// handle requests for /foo with fooAction() method on $object
$dispatcher->any('/foo', array($object, 'fooAction'));
// {details} must be optional because {option} is optional
$dispatcher->get('/users/{username}/{option}/{details}', $action, $headers, ['option' => 'update', 'details' => '']);
// {details} is
$dispatcher->any('/', function () {
return $error404Response;
});
// given these routes...
$dispatcher
->get('/foo/{bar}', 'MyController::getFooAction')
->post('/foo', 'MyController::postFooAction');
// your controller might look like...
class MyController
{
public function getFooAction($bar)
{
...
return $response;
}
public function postFooAction()
{
...
return $response;
}
}
public function someAction()
{
return $request;
}
$dispatcher->any('/', function (Request $request) {
error_log('received request: '.$request->getUri());
});
public function someAction(\Psr\Http\Message\ServerRequestInterface $request)
{
// ...
}
// specify a route called auth_login
$dispatcher->post('/login', 'AuthController::login', [], 'auth_login');
// now you can generate URIs in your actions based on the route
public function someAction()
{
$uri = $dispatcher->generate('auth_login');
// $uri contains '/login'
}
// if you need to change the route, the action will automatically
// generate the correct URI
$dispatcher->post('/auth/login', 'AuthController::login', [], 'auth_login');
$dispatcher->get('/users/{user}', 'UsersController::getUser', [], 'get_user');
// pass the username to use for the {user} parameter
$uri = $dispatcher->generate('get_user', ['user' => 'joe']);
echo $uri; // outputs '/users/joe'