Slim4-notes
Jump to navigation
Jump to search
Beginning of a cheat sheet
Pulled from various sources..
slim4 cheatsheet pada middleware for authentication
Get parsed body
$request->getParsedBody()
- Apparently need some middleware for this to work
$app->addBodyParsingMiddleware();
Returning a redirect
/**
* Create a redirect response;
* @param string $newLocation - where you wish to redirect the user.
* @param Slim\Psr7\Response $response - the existing response to work with
* @param bool $useTemporaryRedirect - whether this redirect is temporary, or browser should cache it.
* @return Slim\Psr7\Response - the redirect response.
*/
function redirect(
string $newLocation,
bool $useTemporaryRedirect=true
) : Slim\Psr7\Response
{
$httpCode = ($useTemporaryRedirect) ? 302 : 301;
$response = new \Slim\Psr7\Response($httpCode);
$response = $response->withHeader('Location', $newLocation);
return $response;
}
Auth Middleware
Not going to bother copy of all the code, but look at the cheetsheet linked above close to the bottom of the page.
Adding a 404 or other err pages
This also looks like a middleware function as it gets called before actually hitting the routes
$app = Slim\Factory\AppFactory::create();
// register any custom middleware....
$app->addMiddleware(new SomeCustomMiddleware());
$app->addMiddleware(new AnotherCustomMiddleware());
// register the error middleware. This must be registered last so that it gets executed first.
$errorMiddleware = $app->addErrorMiddleware(
$displayErrorDetails = (ENVIRONMENT === "dev"),
$logErrors=true,
$logErrorDetails=true
);
// Create your 404 handler...
$errorMiddleware->setErrorHandler(\Slim\Exception\HttpNotFoundException::class, function (
\Psr\Http\Message\ServerRequestInterface $request,
\Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails
) {
$response = new \Slim\Psr7\Response();
$body = new View404();
$view = new ViewCustom404Page();
$response->getBody()->write((string)$view);
return $response->withStatus(404);
});
// register routes/controllers here....
$app->run();