I’ve just found the slim framework. I’m liking it so far but have run into a problem. I’m using it to create an API. I’ve attached a rendering but of middle ware to control how data is shown depending on the accept header (json or html)
Middleware looks like
class RenderController {
public function __invoke( $request, $response, $next )
{
// Set default content type
$response = $response->withHeader('Content-Type', 'application/json');
// Make sure the client is using a correct accept header
$negotiator = new \Negotiation\Negotiator();
$acceptHeader = $request->getHeaderLine('Accept');
$priorities = array('application/json', 'text/html', 'text/plain');
if( ! $mediaType = $negotiator->getBest($acceptHeader, $priorities) )
throw new Exception( "Invalid accept header", 406 );
// Run the requested command and set the return type
$value = $mediaType->getValue();
$type = $mediaType->getType();
$response = $next($request, $response)->withHeader('Content-Type', $type);
// Set the content-type header to that requested
switch( $type )
{
case 'application/json':
$response = $response->withJson( $request->getAttribute( "userData" ) );
break;
case 'text/html':
break;
case 'text/plain':
break;
}
return $response;
}
}
I’ve got my route set up as below
$app->get( '/testTwo/{name}', function( $request, $response, $args )
{
$name = $request->getAttribute( "name" );
$obj = new Test();
$data = $obj->parseName( $name );
$request = $request->withAttribute( "userData", $data );
return $response;
});
The Test class will eventually be the meat of my application and return an associative array of information. My question is, is using the withAttribute method the correct way to move data around. Because in my middleware after invoking $next( $request, $response ) There’s nothing in $request->getAttribute( “userData” ). How do I get the information from my backend application into the middleware?
Or am I going about this the wrong way to begin with?
Thanks