Search code examples
phpreststandards

Is there a standard for corresponding restful PHP functions?


In a restful API for fruit, the request assumes something like this:

api/fruit
api/fruit?limit=100
api/fruit/1
api/fruit?color=red

I think there must be a standard for functions that do the work. For instance, something may easily translate to fruit.class.php.

fruit.class.php

function get ($id, $params, $limit) {
    // query, etc.
}

So for my above examples, the code would look like

  • 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'));
    

Is there an industry standard like this or are API/database functions always a mess? I’d really like to standardize my functions.


Solution

  • No, there is no standard as others have already answered...however, in answer to your issue about creating too many methods...I usually only have a single search() method that returns 1 or more results based on my search criteria. I usually create a "search object" that contains my where conditions in an OOP fashion that can then be parsed by the data layer...but that's probably more than you want to get into...many people would build their DQL for their data-layer, etc. There are a lot of ways to avoid getById, getByColor, getByTexture, getByColorAndTexture. If you start seeing lots of methods to cover every single possible combination of search, then you're probably doing it wrong.

    As to rest method naming...ZF2 is not the answer, but it's the one I"m currently using on my project at work, and its methods are laid out like so (please note, this is HORRIBLE, dangerous code...open to SQL injection...just doing it for example):

    // 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);
    
    }