Implementation of Common Operating Class in PHP-Communication Data Encapsulation Class

Time:2019-8-18

Thank you for your collection and praise, which is my greatest encouragement.

Necessity

Data communication between two ends in B/S architecture and C/S architecture(Note: Communication here refers to network request and reply operations) Inevitably, because there is no data, there is no content, no content, what is the meaning of:)
Generally speaking, the communication execution process of C/S architecture is as follows:

Implementation of Common Operating Class in PHP-Communication Data Encapsulation Class

The B/S architecture communication execution process is like this:

Implementation of Common Operating Class in PHP-Communication Data Encapsulation Class

Choice

Since data communication is unavoidable, which communication mode should be chosen? At present, there are three main ways of data transmission and interaction between server and client: URL, XML and JSON.

URL is the most common and direct way, usually used for GET method. In fact, I think the Form form in POST is also the way of URL in essence, but this way of transmission is limited and not standardized. It is only suitable for some simple scenarios.
Both XML and JSON are essentially descriptions of data. Their purpose is to segment, package and standardize complex data for data transmission and analysis. JSON is lighter but more flexible and powerful than XML. For example, to express my personal information in the above two ways is as follows:

JSON:
    {"name": "entner", "age": 21, "gender": "man"}
    
    XML:
    <ROOT>
        <name>entner</name>
        <age>21</age>
        < gender > male </gender >
    </ROOT>

Interested readers can refer to the following reference links and write in great detail.

How to encapsulate?

As mentioned above, XML and JSON are the mainstream communication data formats at present. Now let’s talk about how to encapsulate and use them conveniently.

Assuming that we get array data by operating database server in the background, it only needs json_encode function for array to Json, which can automatically detect recursively. For array to XML, we need to strictly follow the format, see the code and annotations in detail.

Source Code

<?php
/**
 * TODO: Json format data communication
 * Author:entner
 * time:   2017-5-8
 * version:1.0
 * ready:
        Status code: int $code
        Tip message: string $message
        Message content: array $data
        Array wrapping: array $result
        

   function: 
       Show encapsulates multiple communication data formats
       JsonEncode encapsulates Json format communication data
       XmlToJson encapsulates communication data in XML format
       XmlEncode recursively calls xmlToJson

 */
Class Json{

    const  JSON = "json";

/**
     * Output of communication data in an integrated manner
     *@ param inter code status code
     *@ Param char message prompt
     *@ param array data communication data
     *@ Param string type data type
     *return string
    */    

    public function show($code,$message,$data=array(),$type = self::JSON){
        /* Check whether the status code is legitimate*/
        if(!is_numeric($code)){
            exit();
        }

        $result = array(
            'code'=>$code,
            'message'=>$message,
            'data'=>$data
            );

        /* The format of encapsulated data is determined by the parameters passed by the client, and the default Json format is used.*/
        $type = isset($_GET['format'])? $_GET['format']:self::JSON;

        if($type == 'xml'){
            $this->xmlEnCode($code,$message,$data);
            Exit; // Multiple formats are not allowed concurrently at one time, so it is not necessary to perform the following judgment
        }else if($type == 'json'){
            $this->jsonEncode($code,$message,$data);
            exit ;
        }else if($type == 'array'){
            var_dump($result);
            exit;
        }else{
            // The data format from client is http/ftp/
        }

    }


/**
     * Output Json format communication data
     *@ param inter code status code
     *@ Param char message prompt
     *@ param array data communication data
     *return string
    */    
    public function jsonEnCode($code,$message,$data=array()){
        if(!is_numeric($code)){
            exit();
        }
        $result = array(
            'code'=>$code,
            'message'=>$message,
            'data'=>$data
            );
        Echo json_encode ($result); //json_encode automatically recursively converts array variables
        return true;
    }

    /**
     * Output XML format communication data
     *@ param inter code status code
     *@ Param char message prompt
     *@ param array data communication data
     *return string
    */    
    public function xmlEnCode($code,$message,$data=array()){
        if(!is_numeric($code)){
            exit();
        }
        $result = array(
            'code'=>$code,
            'message'=>$message,
            'data'=>$data
            );

        /* splicing XML format data*/
        
        
        /* It's important to note here the declaration header information and the XML declaration*/
        header("Content-type:text/xml");
        $xml  = "<?xml version = '1.0' encoding = 'UTF-8'?>\n";
        $xml. ="<root>\ n"; /* XML tags are actually strings, so use the. join operator*/
        $xml. = self:: xmlToJson ($result); /* Call the xmlToJson function to parse the array into nodes*/        
        $xml .= "</root>";
        echo $xml;        
    }

    /**
     * Recursive splicing of XML data
     *@ param inter code status code
     *@ Param char message prompt
     *@ param array data communication data
     *return string
    */    
    public static function xmlToJson($data){
        $xml = $attr = "";
        foreach($data as $k => $v){

            /* XML does not allow the appearance of digital labels, so either prize numbers into letters, or mixed stitching, which uses a very good stitching method.*/
            if(is_numeric($k)){
                $attr = " id = '{$k}' ";
                $k = "item";
                $xml .="<{$k}{$attr}>\n";
                /* Because there may be arrays inside the array, you need to check them recursively by yourself. Note that at each recursion, you need to connect to the end of $xml and wrap lines.*/
                $xml .=is_array($v)?self::xmlToJson($v):$v;
                $xml .="</{$k}>\n";
            }else{
                $xml .="<{$k}>\n";
                $xml .=is_array($v)?self::xmlToJson($v):$v;
                $xml .="</{$k}>\n";
            }
            
        }
        return $xml;
    }

}

$data = array(
    
    'name'=>'entner',
    'type'=>array(
            0=>'a',
            1=>'b'
        )
    );
$try = new Json();
$try->xmlEnCode(200,'success',$data);

Reference link

Talking about the Development of PHP and Mobile App, that is API Interface Development
Principle of C/S B/S and WEB
Contrastive Analysis of JSON and XML

epilogue

These days, I’m moving my dormitory. As soon as I’m busy, I’m here at the first time. Ha-ha.
It’s the same old saying. Welcome your comments and comments.