PHP Request and Response Classes for CRUD Operations

This article explains how to implement a PHP Request class that handles CRUD operations based on HTTP methods, a Response class that formats output as JSON, XML, or HTML, and an index entry point that ties the two together for a simple API.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP Request and Response Classes for CRUD Operations

The Request.php file defines a Request class that acts as a data‑operation layer. It supports the HTTP methods GET, POST, PUT, PATCH, and DELETE, routing each method to a corresponding private static function ( getData, postData, putData, patchData, deleteData) which manipulate a static test data array representing class information.

<?php
/**
 * 数据操作类
 */
class Request {
    private static $method_type = array('get','post','put','patch','delete');
    private static $test_class = array(
        1 => array('name'=>'托福班','count'=>18),
        2 => array('name'=>'雅思班','count'=>20),
    );
    public static function getRequest(){
        $method = strtolower($_SERVER['REQUEST_METHOD']);
        if(in_array($method,self::$method_type)){
            $data_name = $method.'Data';
            return self::$data_name($_REQUEST);
        }
        return false;
    }
    private static function getData($request_data){
        $class_id = (int)$request_data['class'];
        if($class_id>0){
            return self::$test_class[$class_id];
        }else{
            return self::$test_class;
        }
    }
    private static function postData($request_data){
        if(!empty($request_data['name'])){
            $data['name'] = $request_data['name'];
            $data['count'] = (int)$request_data['count'];
            self::$test_class[] = $data;
            return self::$test_class;
        }else{
            return false;
        }
    }
    private static function putData($request_data){
        $class_id = (int)$request_data['class'];
        if($class_id==0){return false;}
        $data = array();
        if(!empty($request_data['name']) && isset($request_data['count'])){
            $data['name'] = $request_data['name'];
            $data['count'] = (int)$request_data['count'];
            self::$test_class[$class_id] = $data;
            return self::$test_class;
        }else{return false;}
    }
    private static function patchData($request_data){
        $class_id = (int)$request_data['class'];
        if($class_id==0){return false;}
        if(!empty($request_data['name'])){
            self::$test_class[$class_id]['name'] = $request_data['name'];
        }
        if(isset($request_data['count'])){
            self::$test_class[$class_id]['count'] = (int)$request_data['count'];
        }
        return self::$test_class;
    }
    private static function deleteData($request_data){
        $class_id = (int)$request_data['class'];
        if($class_id==0){return false;}
        unset(self::$test_class[$class_id]);
        return self::$test_class;
    }
}
?>

The Response.php file provides a Response class that formats the data returned by Request. Depending on the incoming Content‑Type, it encodes the data as JSON, XML, or an HTML table and sends the appropriate HTTP headers.

<?php
class Response {
    const HTTP_VERSION = "HTTP/1.1";
    public static function sendResponse($data){
        if($data){
            $code = 200;
            $message = 'OK';
        }else{
            $code = 404;
            $data = array('error'=>'Not Found');
            $message = 'Not Found';
        }
        header(self::HTTP_VERSION . " " . $code . " " . $message);
        $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : $_SERVER['HTTP_ACCEPT'];
        if(strpos($content_type,'application/json')!==false){
            header("Content-Type: application/json");
            echo self::encodeJson($data);
        }elseif(strpos($content_type,'application/xml')!==false){
            header("Content-Type: application/xml");
            echo self::encodeXml($data);
        }else{
            header("Content-Type: text/html");
            echo self::encodeHtml($data);
        }
    }
    private static function encodeJson($responseData){
        return json_encode($responseData);
    }
    private static function encodeXml($responseData){
        $xml = new SimpleXMLElement('<?xml version="1.0"?><rest></rest>');
        foreach($responseData as $key=>$value){
            if(is_array($value)){
                foreach($value as $k=>$v){
                    $xml->addChild($k,$v);
                }
            }else{
                $xml->addChild($key,$value);
            }
        }
        return $xml->asXML();
    }
    private static function encodeHtml($responseData){
        $html = "<table border='1'>";
        foreach($responseData as $key=>$value){
            $html .= "<tr>";
            if(is_array($value)){
                foreach($value as $k=>$v){
                    $html .= "<td>".$k."</td><td>".$v."</td>";
                }
            }else{
                $html .= "<td>".$key."</td><td>".$value."</td>";
            }
            $html .= "</tr>";
        }
        $html .= "</table>";
        return $html;
    }
}
?>

The index.php file serves as the entry point of the application. It includes both Request.php and Response.php, obtains the processed request data via Request::getRequest(), and then passes that data to Response::sendResponse() for output.

<?php
require('Request.php');
require('Response.php');
$data = Request::getRequest();
Response::sendResponse($data);
?>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

APIrequestResponse
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.