Skip to content

Instantly share code, notes, and snippets.

@dmgig
Last active June 14, 2016 00:19
Show Gist options
  • Save dmgig/10117d5bc55c1c18796c61aaa53a58ce to your computer and use it in GitHub Desktop.
Save dmgig/10117d5bc55c1c18796c61aaa53a58ce to your computer and use it in GitHub Desktop.
Slim REST API with Local File Storage
<?php
set_include_path ('/home');
require 'vendor/autoload.php';
\Slim\Slim::registerAutoloader();
const DATALOC = "/home/data";
$allowed_objects = ['tests'];
$app = new \Slim\Slim();
$app->config('debug', true);
/**
* CREATE
*/
$app->post('/:object', function ($object) use ($app) {
$filepath = DATALOC."/$object";
if(!file_exists($filepath)) mkdir($filepath);
$nextfile = $filepath."/".getNextFile($filepath);
$data = $app->request->getBody();
$result = file_put_contents($nextfile, $data);
echo json_encode((bool) $result);
});
/**
* RETRIEVE
*/
$app->get('/:object', function ($object) use ($app) {
$filepath = DATALOC."/$object";
$files = glob($filepath.'/*');
$data = [];
foreach($files as $i => $file){
$filedata = json_decode(file_get_contents($file));
$filedata->id = (int) basename($file);
$data[] = $filedata;
}
echo json_encode($data);
});
$app->get('/:object/:id', function ($object, $id) use ($app) {
$filepath = DATALOC."/$object/$id.json";
$data = json_decode(file_get_contents($filepath));
$data->id = (int) basename($id);
echo json_encode($data);
});
/**
* UPDATE
*/
$app->put('/:object/:id', function ($object, $id) use ($app) {
$filepath = DATALOC."/$object";
$file = $filepath."/{$id}.json";
$data = $app->request->getBody();
$result = file_put_contents($file, $data);
echo json_encode((bool) $result);
});
/**
* DELETE
*/
$app->delete('/:object/:id', function ($object, $id) use ($app) {
$filepath = DATALOC."/$object";
$file = $filepath."/{$id}.json";
$result = unlink($file);
echo json_encode((bool) $result);
});
$app->run();
function getNextFile($filepath){
$files= glob($filepath.'/*');
sort($files); // sort the files from lowest to highest, alphabetically
$file = array_pop($files); // return the last element of the array
$fileid = (int) basename($file);
$nextfileid = $fileid + 1;
$nextfile = $nextfileid.".json";
return $nextfile;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment