3

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

?>
4

1 回答 1

5

有很多方法可以解决这个问题,我建议使用模板方法模式,这样你就可以在父类中定义一个共同的行为,并在子类中处理具体的细节。

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()方法都特定于每个实体。通过在 in 中声明此方法abstractSortPageHandler我们强制所有子类实现此功能。

现在 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();

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

于 2012-11-20T16:49:54.193 回答