Created
August 19, 2012 22:35
-
-
Save njh/3398258 to your computer and use it in GitHub Desktop.
respondTo example in Slim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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(); |
Author
I would prefer:
$app->get('/books/:id/:format', function ($id, $format) use ($app) {
$format = $app->respondTo(ltrim($format, '.'), array('html', 'xml', 'json'));
...
});
or better:
$app->get('/books/:id.:format', function ($id, $format) use ($app) {
$format = $app->request->negotiateFormat($format, array('html', 'xml', 'json'));
...
});
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
Got this working in my branch here:
https://github.com/njh/Slim/tree/negotiation