Routing and Middleware - Gimanh/ZXC_PHP GitHub Wiki
Description
ZXC_PHP
support PSR-7 HTTP
message implementation.
You can define application routes using config file all routes for ZXC_PHP
must be defined in config file ZXC/Router/routes
.
Route item is associative array with two keys before
and route
.
Every route handler accept two required arguments ServerRequestInterface $request
, ResponseInterface $response
, $params
third arguments is optional and isset named parameters from URI.
Route handler must return ResponseInterface $response
object.
public function hello(ServerRequest $request, Response $response)
{
$response->write('Hello');
return $response;
}
Structure
Routes
ZXC/Router/routes
- is array with application routes
'ZXC' => [
'Router' => [
'routes' => [
[
'before' => ['auth'],
'route' => 'POST|/fetch/all/products|Application\App:fetchProducts'
]
]
]
],
before
{ {string} array | callable }
- this key allows you set you middleware for route.
The execution order is as you specified in the array.
route
{ string }
- this key allows you set route params.
Route structure HTTP METHOD | ROUTE | {optional section} Class:methodName
route
- has three sections with separator |
first and second is required third is optional.
First section is HTTP METHOD
second is URI PATH
third is Class and method Class:methodName
separated with :
separator.
Middleware
All middleware accepts three arguments
- Psr\Http\Message\RequestInterface $request
- Psr\Http\Message\ResponseInterface $response
- Closure $next
class MiddlewareAuth
{
public static function check(RequestInterface $request, ResponseInterface $response, Closure $next)
{
$auth = ModulesManager::getModule('auth');
if ($auth->isLoggedIn($request)) {
return $next($request, $response);
}
return $response->withStatus(401);
}
}
Middleware for ZXC_PHP must described in config file ZXC/Router/middleware
see example below.
Defined middleware you can use in route section before
.
Allowed HTTP methods
ZXC_PHP
will accepts only defined methods in config file ZXC/Router/methods
Examples
GET|/|Class:getIndex
- for /
path by the GET
method ZXC_PHP will create instance of Class
and call method methodName
.
POST|/fetch/private/data|Class:fetchPrivateData
HTTP METHOD | ROUTE | {optional section} Class:methodName
With named parameters
POST|/fetch/private/data/for/:user|Class:fetchPrivateData
Config
'ZXC' => [
'Router' => [
'methods' => ['GET' => true, 'POST' => true, 'OPTIONS' => true],
'preflight' => 'DomainRequest:cors',
'middleware' => [
'auth' => 'Application\Authentication:check',
'authAdmin' => 'Application\Authentication:checkAdmin',
],
'routes' => [
[
'before' => ['auth'],
'route' => 'POST|/fetch/all/products|Application\App:fetchProducts'
]
]
],
'Modules' => [],
'Autoload' => [
'../../../server/' => true
]
],