Created
July 26, 2016 11:14
-
-
Save feketegy/2c11009ea61e48b34208fe383c6b41ed to your computer and use it in GitHub Desktop.
psr7 router example using league and diactronos
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Setup the router | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
// Init container and set PSR7 shareables | |
$routeContainer = new League\Container\Container; | |
// Set response type (must be psr7 response interface) | |
$routeContainer->share('response', Zend\Diactoros\Response::class); | |
// Get and parse request (psr7 way) | |
$routeContainer->share('request', function() { | |
return Zend\Diactoros\ServerRequestFactory::fromGlobals( | |
$_SERVER, $_GET, $_POST, $_COOKIE, $_FILES | |
); | |
}); | |
// Setup an emitter so the response will be returned to the client | |
$routeContainer->share('emitter', Zend\Diactoros\Response\SapiEmitter::class); | |
try | |
{ | |
// Map routes | |
$route = new League\Route\RouteCollection($routeContainer); | |
$route->setStrategy(new League\Route\Strategy\JsonStrategy); | |
// Setup the individual routes | |
$route->post('/save', 'Save\Handler::execute'); | |
$route->get('/get','DisplayList\Handler::execute'); | |
// Dispatch the response back to the client | |
$response = $route->dispatch( $routeContainer->get('request'), $routeContainer->get('response') ); | |
$routeContainer->get('emitter')->emit($response); | |
} | |
catch (Exception $e) | |
{ | |
$response = new Zend\Diactoros\Response\JsonResponse([ | |
'exception' => $e, | |
'message' => $e->getMessage() | |
], 400); | |
$routeContainer->get('emitter')->emit($response); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment