Hello all! New to Slim, and first time new to here. I have a primary question and a general question.
- Primarily, I would like to allow SomeResource::doSomething() to validate its scope of work, and if there is an error, return the HTTP status code back to Slim so it might be returned to the client. I tried to have SomeResource::doSomething() execute
http_response_code(400)
;, and have slim check the code and forward it, but slim still sees 200. How is this accomplished? - Generally, can anyone give a quick review of the below code, and provide any constructive criticism.
Thanks!
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
require __DIR__.'/../vendor/autoload.php';
spl_autoload_register(function ($classname) {
$parts = explode('\\', $classname);
require __DIR__."/../classes/".end($parts).".php";
});
$settings=[
'settings'=>[
'db'=>parse_ini_file(__DIR__.'/../../db.ini',true)
],
'displayErrorDetails'=> true,
'determineRouteBeforeAppMiddleware' => true //Not sure if this is necessary
];
$container = new \Slim\Container($settings);
$container['pdo'] = function ($container) {
$cfg = $container->get('settings')['db'];
return new \PDO($cfg['dsn'], $cfg['user'], $cfg['password']);
};
$container['someResource'] = function ($container) {
return new someResourceMapper($container->get('pdo'));
};
$app = new \Slim\App($container);
$app->get('/', function($request, $response) {
return $response->withJson($this->get('someResource')->doSomething())->withStatus($response->getStatusCode());
});
$app->add(function(Request $request, Response $response, $next) {
// Use middleware for authentication. Be sure to put as last route so it is executed first
if (invalidUser()) {
return $response->withJson(\MyApp\ErrorResponse::invalidUser(), 401);
}
// If desired, add something to the container
$this['account'] = [123];
return $next($request, $response);
});
// Forgot why I am doing this...
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->run();