-
Notifications
You must be signed in to change notification settings - Fork 0
Routing
Joshua Parker edited this page Aug 21, 2020
·
9 revisions
Below is a basic example of setting up a route. The route's first parameter is the uri, and the second parameter is a closure or callback.
/**
* Step 1: Require autoloader and import a few needed classes.
*/
require('vendor/autoload.php');
use Qubus\Router\Router;
use Qubus\Router\RouteCollector;
/**
* Step 2: Instantiate the Router.
*/
$router = new Router(new RouteCollector);
$router->setBasePath('/'); // This assumes root directory.
/**
* Step 3: Include the routes needed
*/
// Prints `Hello world!`.
$router->get('/hello-world/', function () {
return 'Hello world!';
});
In passing a closure as a route handler, you need to pass in two arguments: Psr\Http\Message\ServerRequestInterface
and Psr\Http\Message\ResponseInterface
. Qubus Router requires Laminas/Diactoros. This library includes two classes that implement the two needed interfaces.
/**
* Step 1: Require autoloader and import a few needed classes.
*/
require('vendor/autoload.php');
use Laminas\Diactoros\Response;
use Laminas\Diactoros\ServerRequestFactory as Request;
use Qubus\Router\Router;
use Qubus\Router\RouteCollector;
/**
* Step 2: Instantiate the Router.
*/
$router = new Router(new RouteCollector);
$router->setBasePath('/'); // This assumes root directory.
/**
* Step 3: Include the routes needed
*/
// Get hello-world route.
$router->get('/hello-world/', function (Request $request, Response $response) {
$response->getBody()->write('Hello World!');
return $response;
});
namespace Qubus\Router;
class UserController
{
public function create()
{
}
public function read()
{
return 'Read user details.';
}
public function update()
{
}
public function delete()
{
}
}
// The example UserController class above has 4 methods create,read,update,delete
// create => POST user/create
// read => GET with optional parameter user/read/
// update => PUT with optional parameter user/update/
// delete => DELETE with optional parameter user/delete/
$router->crud('/user', '\Qubus\Router\UserController');
// disable some methods
$router->crud('/user', '\Qubus\Router\UserController', ['c']); // only create
$router->crud('/user', '\Qubus\Router\UserController', ['create']); // only create
$router->crud('/user', '\Qubus\Router\UserController', ['c', 'u']); // create & update
$router->crud('/user', '\Qubus\Router\UserController', ['create', 'update']); // create & update
// named crud
$router->crud('/user', '\Qubus\Router\UserController', null, 'named.crud'); // name can be used for redirection