<?php
// Initialization common to all operations
// Get configured (as 'theDB' in zero.config) DataManager for data access
$dataManager = data_manager('theDB');
class Employees {
function onList() {
global $dataManager;
// Retrieve employee records via Query Zero
$employeeRecords = dataExec($dataManager, "SELECT * FROM employees");
// Use the zero global context to render the data as JSON
zput('/request/view', 'JSON');
zput('/request/json/output', $employeeRecords);
render_view();
}
function onCreate() {
global $dataManager;
// Convert the raw JSON stream in to a PHP array
$er = json_decode($HTTP_RAW_POST_DATA);
$result = dataExec($dataManager, "INSERT INTO employees (username, , location, phonenumber) ".
"VALUES (?, ?, ?, ?, ?)", array($er['username'], $er['location'], $er['phonenumber']));
// Set a Location header with URI to the new record
$locationUri = get('/request/path') . "/" . $er["username"];
zput('/request/headers/out/Location', $locationUri);
zput('/request/status', 204);
}
function onRetrieve() {
// Get configured DataManager for data access
global $dataManager;
// Zero puts 'itemId' when accessing restful resources
$username = zget("/request/params/employeesId");
// Retrieve employee record via Query Zero
$employeeRecord = dataQueryFirst($dataManager, "SELECT * FROM employees WHERE username=?", array($username));
if(isset($employeeRecord)) {
// JSON encode employee record
zput('/request/headers/out/Content-Type', 'text/json');
echo json_encode($employeeRecord);
} else {
// Error handling; return a custom error page
zput("/request/status", 404);
echo "username ". $username . " not found.";
}
}
function onUpdate() {
// Get configured DataManager for data access
global $dataManager;
// By convention, Zero places posted text/json into the GC as a JSON object
$er = json_decode($HTTP_RAW_POST_DATA);
$result = dataExec($dataManager, "UPDATE employees location=?, phonenumber=? WHERE username=?",
array($er['firstname'], $er['phonenumber'], $er['username']));
zput("/request/status", 204);
}
function onDelete() {
// Get configured DataManager for data access
global $dataManager;
$username = zget("/request/params/employeesId");
// Delete employee record via Query Zero
$result = dataExec($dataManager, "DELETE FROM employees WHERE username=?", array($username));
zput("/request/status", 204);
}
}
?>