php - 对应的restful PHP函数有没有标准?

标签 php api rest standards coding-style

在 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/

相关文章:

jquery - 如何将 x.509 证书添加到 Restful WCF 服务?

php - 如何控制在 symfony1.4 任务中从 database.yml 中选择哪个连接

PHP while 循环中的第二个 while 循环仅运行一次

php - 计算 JSON 有效负载的大小(以字节为单位),包括在 PHP 的 JSON 有效负载中

ruby-on-rails - 如何将项目添加到 json 对象 ruby​​ on rails?

java - Android YoutubePlayer API 崩溃

api - 如何通过 API 以编程方式在 Microsoft Store 上创建订阅加载项

php - Symfony 3.4 使用 RESTful API 插入数据,无需捆绑

node.js - NodeJS REST土耳其字,Socket挂掉

php - include header.php css,不会在 include footer.php 或 body 上工作