I have been experimenting with the current version of the wonderful package for routing from thephpleague.
I have a simple index page to handle the routing and it works just fine.
<?php declare(strict_types=1);
use Laminas\Diactoros\ServerRequestFactory;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Laminas\Diactoros\ResponseFactory;
use League\Route\Router;
use League\Route\Strategy\JsonStrategy;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
$strategy = new JsonStrategy(new ResponseFactory());
$router = new Router;
$router->setStrategy($strategy);
$router->post(
'/hello',
function (ServerRequestInterface $request): ResponseInterface
{
var_dump($request->getParsedBody());
}
);
$request = ServerRequestFactory::fromGlobals(
$_SERVER,
$_GET,
$_POST,
$_COOKIE,
$_FILES
);
$response = $router->dispatch($request);
// send the response to the browser
(new SapiEmitter)->emit($response);
My problem is when I send a POST request with JSON data in it, I am unable to capture it in my code as indicated by the line var_dump($request->getParsedBody());.
At the moment, the only way I am able to capture the data sent with the request is by running json_decode(file_get_contents('php://input'), true);.
What I do need to do in order to get the payload sent with whatever request, be it GET, POST, PUT, PATCH, or otherwise?
Thank you.
I finally figured it out. After close examination, I think using dependency injection,
ServerRequestInterfaceis mapped toLaminas\Diactoros\ServerRequest.So, to illustrate
where
$request->getHeaders()gives you the request headers$request->getParsedBody()will return to all the data as an array sent through when the headerContent-Type: multipart/form-datais set (at least as far as I have experimented)$request->getQueryParams()gives all the query string params as an array just like$_GET$request->getUploadedFiles()gives all the the uploaded files as an array of instances ofLaminas\Diactoros\UploadedFile$request->getBody()->getContents()will return to all data the as a string when the headerContent-Type: application/jsonis set. You can then runjson_decode($request->getBody()->getContents(), true)to get the actual contents an array