[Laravel] 10 - WEB API : wrapper

前言


一、常用的解决方案

React 前端 + PHP (Laravel) 后端

Such as "some exposure to WEB API’s and/or RESTful“。

使用PHP,但不必关心 return view,那么我们应该关心什么呢?

 

 

二、本篇提到的接口

Ref: PHP开发APP接口

 服务端发送 - html

[1] 不是php面相对象的接口,而是app接口,以下就是个例子(URL):

[2] APP (通信) 接口定义,仨条件:

    • 接口地址
    • 接口文件
    • 接口数据

 

 客户端返回 - json/xml

一般返回xml或者json格式的内容,在此列出基本方法:

JSON XML
json_encode($arr) $return .= 拼装法
  $dom = new DomDocument(...);
  XMLWriter
  XMLWriter

 

 

 

封装通信接口


一、封装方法

三种封装的方式:  

 

 

 

二、PHP return JSON

  • Only UTF-8, value is Array.
json_encode($value)

 

  • 字符编码转换
$newData = iconv('UTF-8', 'GBK', $data) 

  

  • 通信数据的三个格式

对应如下代码的参数:

[封装方法]

class
Response {   public static function json($code, $message = '', $data = array()) {     if (!is_numeric($code)) {       return '';     }
/**
* 组装成一个新的数据
*/     
$result = array(       'code' => $code,       'message' => $message,       'data' => $data     );     echo json_encode($result);     exit; }

 

Next, 实践上述类和方法。

<?php

require_once('./response.php');
$arr = array   'id' => 1,   'name' => 'singwa' ); Response::json(200, '数据返回成功’, $arr);

 

 

三、PHP return XML

  • PHP生成XML数据
1) 组装字符串
2) 使用系统类
    DomDocument --> http://php.net/manual/en/class.domdocument.php
    XMLWriter   --> http://php.net/manual/en/book.xmlwriter.php
    SimpleXML --> http://php.net/manual/en/book.simplexml.php

 

  • 构建XML文件

对应的代码生成。在以上的json的response类中添加以下函数:

public static function xml() {
  //header("Content-Type:text/xml");
//以xml形式表现结构,这么用户接收到response时,就能有xml的友好格式展示
  
$xml = "<?xml version= '1.0' encoding='UTF-8'?>\n";   $xml .= "<root>\n";   $xml .= "<code>200</code>\n";   $xml .= "<message>数据返回成功</message>\n";   $xml .= "<data>\n";   $xml .= "<id>1</id>\n";   $xml .= "<name>singwa</name>\n";   $xml .= "</data>\n";   $xml .= "</root>\n";   echo $xml; }

输入URL:

app.com/response.php 

生成:
 

  

  • 封装通信接口数据

[1] 用户用到的代码示范。

$data = array(
  'id'   => 1,
  'name' => 'singwa',
);

Response::xmlEncode(200, 'success', $data);

[2] 封装函数的实现。

public static function xmlEncode($code, $message, $data = array()) {

  if (! is_numeric($code)) {
    return '';
  }

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

  header("Content-Type:text/xml");

  $xml = "<?xml version= '1.0' encoding='UTF-8'?>\n";
  $xml .= "<root>\n";
  $xml .= self::xmlToEncode($result);  # --->
  $xml .= "</root>\n";

  echo $xml; }

[3] XML对具体内容的封装。

public static function xmlToEncode($data) {

  foreach( $data as $key => $value) {
    $xml .= "<{$key}>";
    $xml .= $value;      // 这里可以改为递归,然后便能打印出内部的数据
    $xml .= "</{$key}>";  
  }

  return $xml;
}

 

[3.1] 改进后加入递归。

public static function xmlToEncode($data) {

  foreach( $data as $key => $value) {
    $xml .= "<{$key}>";
    $xml .= is_array($value)?self::xmlToEncode($value):$value;
    $xml .= "</{$key}>";  
  }

  return $xml;
}

 

[3.2] 如果value部分是数组,会引出一个问题如下。

$data = array(
  'id'   => 1,
  'name' => 'singwa',
  'type' => array(4,5,6)
); Response::xmlEncode(200, 'success', $data);

   但,标签是不能用数字表示的。

<type>
  <0>4</0>
  <1>5</1>
  <2>6</2>
</type> 

改进方案:$key的角色变了,由<id>变为<item attr = "_">;既然此时的标签没有意义,那就拿item来顶替好了。

public static function xmlToEncode($data) {

  $xml = $attr = "";
  foreach( $data as $key => $value) {

    if (is_numberic($key)) {
      $attr = "id='{$key}'";
      $key  = "item";
    }

    $xml .= "<{$key}><{$attr}>";
    $xml .= is_array($value)?self::xmlToEncode($value):$value;
    $xml .= "</{$key}>";  
  }

  return $xml;
}

显示结果:

 

 

 

综合通信方式封装 


一、何为”综合“

就是通过判断type: json or xml,从来具体类型具体封装。

show( $code, $message, $data=array(), $type='json' )

 

二、代码示范

    /**
    * 按综合方式输出通信数据
    * @param integer $code 状态码
    * @param string $message 提示信息
    * @param array $data 数据
    * @param string $type 数据类型
    * return string
    */
    public static function show($code, $message = '', $data = array(), $type = self::JSON) {
        if(!is_numeric($code)) {
            return '';
        }

/* url中的参数判断 */
$type = isset($_GET['format']) ? $_GET['format'] : self::JSON; $result = array( 'code' => $code, 'message' => $message, 'data' => $data, ); if($type == 'json') { self::json($code, $message, $data); exit;
}
elseif($type == 'array') { var_dump($result);
}
elseif($type == 'xml') { self::xmlEncode($code, $message, $data); exit;
}
else { // TODO } }

 

posted @ 2018-07-08 20:29  郝壹贰叁  阅读(390)  评论(0编辑  收藏  举报