我正在使用 Slim PHP 框架为我的应用程序创建一个 RESTful API。我希望所有 URL 都能够接受用于排序和分页的参数。有人能告诉我最好的方法吗?
另外,有人可以为我提供一些适当的 REST URI 吗?(即http://domain.com/api/category/fruit/?sort=DESC&results=25&page=2)
<?php
require 'Slim/Slim.php';
$sort = "ASC";
$results = 10;
$page = 1;
$app = new Slim();
$app->get('/wines', function () use ($app) {
$sort = $app->request()->params('sort');
$results = $app->request()->params('results');
$page = $app->request()->params('page');
getWines();
});
$app->get('/categories', function () use ($app) {
$sort = $app->request()->params('sort');
$results = $app->request()->params('results');
$page = $app->request()->params('page');
getCategories();
});
$app->get('/sub-categories', function () use ($app) {
$sort = $app->request()->params('sort');
$results = $app->request()->params('results');
$page = $app->request()->params('page');
getSubCategories();
});
$app->run();
function getWines() {
$sql = "select * FROM wine ORDER BY name " . $sort . " LIMIT " . $page . " , $results";
try {
$db = getConnection();
$stmt = $db->query($sql);
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"wine": ' . json_encode($wines) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>