How does PHP implement the class of operations (communication data encapsulation)?

Source: Internet
Author: User
Tags php class
PHP class encapsulation for beginners is more difficult to understand, the following this article mainly introduces the PHP common operation class of communication data encapsulation class implementation of the relevant data, the text through the sample code introduced in very detailed, for everyone has a certain reference learning value, Friends who need to follow the small series together to learn together.

Objective

This article mainly introduces about PHP common operation class of communication data encapsulation class implementation of the relevant content, share out for everyone to reference the study, the following words do not say, come together to see the detailed introduction:

Necessity

No matter in the B/s architecture, or the C/s architecture, the data communication at both ends (note: Communication here refers to the network request and reply operation) is unavoidable, because there is no data there is no content, no content, and what is the point:)

Generally speaking, C/S architecture communication execution flow is as follows:

and b/S architecture communication execution flow like this:

Choose

Since data communication, inevitably, that should choose which kind of communication is better? At present, the server and the client for data transmission and interaction of the main way is the URL, XML, json three ways.

URL mode is the most common and most direct, usually used for get methods, in fact, I think the form form in post is essentially a URL method, but this transmission mode of data is limited, is not standardized, only suitable for some simple scenarios. XML and JSON is essentially a description of the data, the purpose is to split the complex data, packaging, normalization, such as a series of processing, convenient data transmission and parsing, relatively speaking, JSON is lighter than XML but more flexible and powerful, for example: In the above two ways to express my personal information is as follows:

JSON: {"name": "Entner", "age": +, "gender": "Male"}  XML: <ROOT>  <name>entner</name>  < age>21</age>  <gender> men </gender> </ROOT>

Interested readers, you can see the following reference links, written in very detailed.

How to encapsulate?

Above, XML and JSON is the mainstream of the current communication data format, the following is about how to encapsulate, easy to use.

Suppose we get the array data in the background Operation database server, for the array to JSON only need json_encode function is enough, it will automatically recursive detection, for the array to XML, you need to strictly follow the format, the specific look at the code and comments it.

Source Code

<?php/** * Todo:json Format Data communication * Author:entner * time:2017-5-8 * version:1.0 * Ready: Status code: INT $code hint message: string $MESSAG E message content: Array $data arrays wrapper: Array $result function:show package multiple communication data formats Jsonencode encapsulate JSON format communication data Xmltojson encapsulated XML format communication data x Mlencode recursive call Xmltojson */class json{const JSON = "JSON";/** * output communication data in an integrated manner * @param Inter Code status code * @param char Message Message hint * @param array Data Traffic data * @param string type data type *return String */Public function Show ($code, $message, $data =arra  Y (), $type = Self::json) {/* check if the status code is valid */if (!is_numeric ($code)) {exit ();  } $result = Array (' code ' = = $code, ' message ' = = $message, ' data ' = $data); /* Parameters that are passed by the client determine the format of the encapsulated data, the default JSON format */$type = isset ($_get[' format ')?  $_get[' format ']:self::json;   if ($type = = ' xml ') {$this->xmlencode ($code, $message, $data); Exit   Concurrent multiple formats are not allowed 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 for the client is http/ftp/}}/** * Output JSON format communication data * @param Inter code status code * @param char Message 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 will automatically recursively convert the array variable 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 *//* Here is important to note 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 them. Join operator */$xml. = Self::xmltojson ($result);  /* Call the Xmltojson function to parse the array into nodes */$xml. = "</root>"; Echo $xml; }/** * Recursive concatenation of XML data * @param Inter code status code * @param char message MSG hint * @param array data communication data *return String */Public s  tatic function Xmltojson ($data) {$xml = $attr = "";  foreach ($data as $k + $v) {/*xml does not allow digital labels, so either the award numbers are converted to letters, or mixed stitching, which is used in a very close-up way */if (Is_numeric ($k)) {$attr = "id =    ' {$k} ';    $k = "Item";    $xml. = "<{$k} {$attr}>\n";    /* Because there may be an array inside the array, you need to check it yourself recursively, note that at each recursive time, you must connect to the tail of the $xml, and wrap the line/$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->xmlencod E (A, ' success ', $data);

summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.