我有一项任务,我需要制作一个简单的API,而且我对如何制作一个API知之甚少。我有一个有员工的数据库。每个员工都有一个id。我正在努力实现这样的目标:
当用户在浏览器中输入时:localhost/index.php?cmd=employees&id=1
它会获得一个JSON数组,其中包含ID为1的用户的信息。我让所有员工都能使用,但不是针对特定员工。我怎样才能做到这一点?我的代码如下:
的functions.php:
<?php
$args = [];
@include_once('apifunctions.php');
function debug($arg)
{
echo '<pre>';
print_r($arg);
echo '</pre>';
}
function sendData($arg)
{
header('Content-Type: application/json');
echo json_encode($arg);
}
function getArguments()
{
if($_SERVER['REQUEST_METHOD'] == 'GET') {
return $_GET;
}
if($_SERVER['REQUEST_METHOD'] == 'POST') {
return $_POST;
}
}
function dispatchRequest()
{
global $args;
$return_value = [];
if(isset($args['cmd'])) {
switch(strtolower($args['cmd'])) {
case 'personeel':
$return_value = getAllEmployees();
break;
case 'afdelingen':
$return_value = getAllDepartments();
break;
case 'managers':
$return_value = getAllManagers();
break;
case 'personeelbyid':
$return_value = getEmployeeById($args['id']);
}
}
return $return_value;
}
apifunctions.php:
<?php
@include_once('dbfunctions.php');
public function getAllEmployees()
{
$personeel = [];
if(dbConnect()) {
if(dbQuery('SELECT * FROM personeel'))
$personeel = dbGetAll();
dbClose();
}
return $personeel;
}
public function getAllDepartments()
{
$afdelingen = [];
if(dbConnect())
{
if(dbQuery('SELECT * FROM afdelingen'))
$afdelingen = dbGetAll();
dbClose();
}
return $afdelingen;
}
public function getAllManagers() {
$managers = [];
if(dbConnect())
{
if(dbQuery('SELECT * FROM personeel WHERE id = 5'))
$managers = dbGetAll();
dbClose();
}
return $managers;
}
public function getEmployeeById($id) {
}
public function getDepartmentEmployeeByDepartmentId() {
$departmentEmployees = [];
if(dbConnect())
{
if(dbQuery(''))
$departmentEmployees = dbGetAll();
dbClose();
}
return $departmentEmployees;
}
的index.php:
<?php
@include_once('app/functions.php');
if (!isset($_GET['cmd']) && !isset($_GET['custid'])) {
if(!isset($_POST['cmd']) && !isset($_POST['custid'])) {
header('HTTP/1.1 403 Not allowed to start this way');
exit(0);
}
}
$args = getArguments();
sendData(dispatchRequest());
也许这是有趣的,我正在使用Postman看看它是否有效。
提前致谢