php – 如何使用Slim接受所有REST URI中的排序和分页参数?

我正在使用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() .'}}'; 
  }
}

?>

解决方法:

有很多方法可以解决这个问题,我建议使用Template Method pattern,因此您在父类中定义了一个常见行为,并处理子类中的特定细节.

abstract class SortPageHandler {
  public function getUrlHandler($app) 
  {
    $me = $this;
    return function () use ($app, $me) {
      $sort = $app->request()->params('sort');
      $results = $app->request()->params('results');
      $page = $app->request()->params('page');

      $app->response()->write($me->getItems($sort, $results, $page));
    };
  }

  abstract public function getItems($sort, $results, $page);
}

class WineHandler extends SortPageHandler {
  public function getItems($sort, $results, $page) 
  {
    //return wines
  }

}

class CategoryHandler extends SortPageHandler {
  public function getItems($sort, $results, $page) 
  {
    //return categories
  }
}

class SubCategoryHandler extends SortPageHandler {
  public function getItems($sort, $results, $page) 
  {
    //return sub-categories
  }
}

因此,父类SortPageHandler使用Slim以及分页和排序所需的函数来处理公共部分.每个getItems()方法都特定于每个实体.通过在SortPageHandler中声明此方法abstract,强制所有子类实现此功能.

现在Slim代码看起来很干净:

$app = new \Slim\Slim();

$wineHandler = new WineHandler();
$categoryHandler = new CategoryHandler();
$subCategoryHandler = new SubCategoryHandler();

$app->get('/wines', $wineHandler->getUrlHandler($app));
$app->get('/categories', $categoryHandler->getUrlHandler($app));
$app->get('/sub-categories', $subCategoryHandler->getUrlHandler($app));

$app->run();

与往常一样,您可以进一步重构此代码,但它可以让您了解如何解决此问题.

上一篇:php – Slim Framework /公用文件夹重定向


下一篇:php – Slim Framework和Ember.js中的Access-Control-Origin