iamdev/rest-in-peace

REST server made easy

Installs: 10

Dependents: 0

Suggesters: 0

Security: 0

pkg:composer/iamdev/rest-in-peace

1.0.0 2024-01-17 02:23 UTC

This package is not auto-updated.

Last update: 2025-12-18 09:44:10 UTC


README

A simple way to provide a REST api on php projects. Follows general directives from https://www.restapitutorial.com/lessons/restquicktips.html.

How simple?

well,

use iamdev\rest\Rest;

Rest::inPeace(
    [
        'users' => new Users(),
        'songs' => new Songs(),
        'playlists' => new Playlists(),
    ],
);

This code will handle routes like /users/1/songs or /users/3/playlists/2/songs by simply implementing Restifier

use iamdev\rest\Context;
use iamdev\rest\Restifier;

class Playlists implements Restifier
{
    public function list(Context $context): ?array
    {
        //return a list ;
    }

    public function create(object $resource, Context $context): string
    {
        //create a $resource 
        //return the new id;
    }

    public function retrieve($id, Context $context): object
    {
        // return a resource with id $id
    }

    public function update($id, $resource, Context $context)
    {
        // update the $resource
    }

    public function delete($id, Context $context)
    {
        // delete $id
    }
}

see this app for more complete implementations

Installation

php composer.phar require "iamdev/rest"

Handling nested routes

GET /users/3/playlists/2/songs will call in order:

  • Users.php#retrieve(3)
  • Playlists.php#retrieve(2)
  • Songs.php#list()

Let's say you are using lazy loading and don't want to call 3 times your database, you can take advantage of Context:

  • isLeaf indicates if the restifier is at the end of the route, so, in the example when on Users.php, it will be false and true on Songs.php
  • resourceMap indicates the differents parts of the routes, in this case it will contain
    array(3) {
    ["users"]=> "3"
    ["playlists"]=> "2"
    ["songs"]=>  NULL
    }
    

    see Users.php

Options

Parameters for Rest::inPeace are (array $routes, $path = null, array $ioHandlers = [])

$path By default, path is resolved as parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), if this doesn't work for you, use this parameter.

$ioHandlers is an array of objects implementing IOHandler. By default, there are 2 implementations for json an XML. If you need to replace it or add a new format use this parameter.

see this example using this options

Notes

In order to use the default route strategy, you will need rewrite your urls, like for apache

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^api(.*)$ with_options.php [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ simple.php [L,QSA]

If not, your routes would need to be like index.php/users/1 and you will have to delete the index.php before calling Rest::inPeace

Exceptions

Simply throw these exceptions to handle http status response: