Citizen Citizen - 2 years ago 58
PHP Question

Is there a standard for corresponding restful PHP functions?

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


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


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.

Answer Source

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 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'];
// for PUT URL /api/fruit/3
public function update( $id, $putArray ) {
    $fruit = getById($id);
    $fruit->color = $putArray['color'];
// for DELETE /api/fruit/3
public function delete( $id ) {
    $fruit = getById($id);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download