在 fruit 的 restful API 中,请求假设是这样的:
api/fruit
api/fruit?limit=100
api/fruit/1
api/fruit?color=red
我认为必须有一个执行这项工作的函数的标准。例如,某些内容可能很容易转换为 fruit.class.php
。
fruit.class.php
function get ($id, $params, $limit) {
// query, etc.
}
所以对于我上面的例子,代码看起来像
api/fruit
$fruit = $oFruit->get();
api/fruit?limit=100
$fruit = $oFruit->get(NULL, NULL, 100);
api/fruit/1
$fruit = $oFruit->get(1);
api/fruit?color=red
$fruit = $oFruit->get(NULL, array('color' => 'red'));
是否有这样的行业标准,或者 API/数据库功能总是一团糟?我真的很想标准化我的功能。
最佳答案
不,没有其他人已经回答过的标准......但是,为了回答你关于创建太多方法的问题......我通常只有一个 search() 方法返回 1 个或多个结果基于我的搜索条件。我通常创建一个“搜索对象”,其中包含我的 OOP 方式的 where 条件,然后可以由数据层解析......但这可能比你想进入的要多......许多人会为他们的 DQL 构建他们的data-layer等。有很多方法可以避免getById,getByColor,getByTexture,getByColorAndTexture。如果您开始看到很多方法来涵盖搜索的每一个可能组合,那么您可能做错了。
至于 rest 方法命名...ZF2 不是答案,但它是我目前在工作项目中使用的方法,它的方法布局如下(请注意,这是可怕的、危险的代码...对 SQL 注入(inject)开放...例如只是这样做):
// for GET URL: /api/fruit?color=red
public function getList() {
$where = array();
if( isset($_GET['color']) ) {
$where[] = "color='{$_GET['color']}'";
}
if( isset($_GET['texture']) ) {
$where[] = "texture='{$_GET['texture']}'";
}
return search( implode(' AND ',$where) );
}
// for GET URL: /api/fruit/3
public function get( $id ) {
return getById( $id );
}
// for POST URL /api/fruit
public function create( $postArray ) {
$fruit = new Fruit();
$fruit->color = $postArray['color'];
save($fruit);
}
// for PUT URL /api/fruit/3
public function update( $id, $putArray ) {
$fruit = getById($id);
$fruit->color = $putArray['color'];
save($fruit);
}
// for DELETE /api/fruit/3
public function delete( $id ) {
$fruit = getById($id);
delete($fruit);
}
关于php - 对应的restful PHP函数有没有标准?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21001277/