-
Notifications
You must be signed in to change notification settings - Fork 0
Middlewares
John Aldrich Bernardo edited this page Feb 12, 2018
·
3 revisions
<?php
// Include autoload
require('./vendor/autoload.php');
use \Calf\HTTP\Router as Router;
use \Calf\HTTP\Route as Route;
use \Calf\HTTP\RouteGroup as RouteGroup;
use \Calf\HTTP\Request as Request;
use \Calf\HTTP\Response as Response;
// Create a new instance of Calf Router
$router = new Router();
// Then create a new Route
$home = new Route('/', function(Request $req, Response $res, array $args) {
return $res->set('Hello World');
});
// For some reason, you might need to use middlewares...
$home->addMiddleware(function(Request $req, Response $res, callable $next) {
// Before route is called,
// Some codes might go here...
// Call the next middleware
$next($req, $res);
// After route is executed.
$res->set($res->get() . '!');
return $res;
});
// Finally after creating a route you'll be
// needing to register it on our router
$router->add($home);
// Then let the Router do its work.
$response = $router->dispatch();
// Render response
$response->render();Hello World!
Implementing a class as Middleware requires __invoke function to be declared and it's suggested to implement \Calf\HTTP\Interfaces\Middleware
<?php
class TestMiddleware implements \Calf\HTTP\Interfaces\Middleware
{
function __invoke(Request $req, Response $res, callable $next) {
$next($req, $res);
$res->set($res->get() . '!');
return $res;
}
}<?php
// Include autoload
require('./vendor/autoload.php');
use \Calf\HTTP\Router as Router;
use \Calf\HTTP\Route as Route;
use \Calf\HTTP\RouteGroup as RouteGroup;
use \Calf\HTTP\Request as Request;
use \Calf\HTTP\Response as Response;
// Create a new instance of Calf Router
$router = new Router();
// Then create a new Route
$home = new Route('/', function(Request $req, Response $res, array $args) {
return $res->set('Hello World');
});
// For some reason, you might need to use middlewares...
$home->addMiddleware(new TestMiddleware());
// Finally after creating a route you'll be
// needing to register it on our router
$router->add($home);
// Then let the Router do its work.
$response = $router->dispatch();
// Render response
$response->render();Hello World!
The calf is open-sourced software licensed under the MIT license.