Skip to content

Instantly share code, notes, and snippets.

@njh
Created August 19, 2012 22:35
Show Gist options
  • Select an option

  • Save njh/3398258 to your computer and use it in GitHub Desktop.

Select an option

Save njh/3398258 to your computer and use it in GitHub Desktop.
respondTo example in Slim
<?php
require 'Slim/Slim.php';
// Prepare app
$app = new Slim(array(
'negotiation.enabled' => true
));
$app->get('/books/:id:format', function ($id) use ($app) {
$format = $app->respondTo('html', 'xml', 'json');
$data = do_something_to_get_data($id);
switch($format) {
case 'html':
return $app->render('myTemplate.php', $data);
case 'xml':
$xml = do_something_to_make_xml($data);
return $app->response()->write($xml);
case 'json':
$json = json_encode($data);
return $app->response()->write($json);
}
});
// Run app
$app->run();
@njh

njh commented Aug 20, 2012

Copy link
Copy Markdown
Author

Got this working in my branch here:
https://github.com/njh/Slim/tree/negotiation

@thomas-0816

Copy link
Copy Markdown

I would prefer:
$app->get('/books/:id/:format', function ($id, $format) use ($app) {
$format = $app->respondTo(ltrim($format, '.'), array('html', 'xml', 'json'));
...
});

@thomas-0816

Copy link
Copy Markdown

or better:
$app->get('/books/:id.:format', function ($id, $format) use ($app) {
$format = $app->request->negotiateFormat($format, array('html', 'xml', 'json'));
...
});

@thomas-0816

Copy link
Copy Markdown

and:

$app = new Slim();
$app->get('/books/:id\.:format', function ($id) use ($app) {
  $app->request->setContentType('html');
  echo "...";
})->conditions(array('format' => 'html'));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment