PHP 개발 APP 인터페이스 전 과정 (1)

25369 단어 mysqlwamp5app
1. 학습 요점: 서버 측 – > 데이터베이스 | 캐 시 – > 호출 인터페이스 – > 클 라 이언 트 2, APP 인터페이스 소개: (PHP 개발 APP 인터페이스) PHP 대상 을 대상 으로 하 는 인터페이스: 추상 류, interface 정의 = > interface. php = = = > 1. APP 인터페이스 (통신 인터페이스): 인 터 페 이 스 를 통 해 데 이 터 를 얻 을 수 있 습 니 다.APP 에 데 이 터 를 채 워 넣 기 - > APP 개발 자 관심: APP 주소 (인터페이스 주소) 요청 + 데이터 APP (통신) 인터페이스 정의 되 돌리 기: 1. 인터페이스 주소:http://app.com/api.php?format=xml 2. 인터페이스 파일: app. php 처리 업무 논리 3. 인터페이스 데이터
3. 클 라 이언 트 APP 통신: APP 가 어떻게 통신 을 하 는 지:
      C          (    :http://app.com/api.php?format=xml/json)                                   S
      APP   ------------------------------>     
               

4. 클 라 이언 트 APP 통신 형식 차이 1. xml: 확장 태그 언어 (1. 데 이 터 를 표시 하고 데이터 유형 을 정의 하 는 데 사용 되 며 사용자 가 자신의 태그 언어 를 정의 할 수 있 는 소스 언어 로 xml 형식 이 통일 되 고 크로스 플랫폼 과 언어 로 데이터 전송 과 통신 에 매우 적합 하 며 업계 에서 공 인 된 기준 이 되 었 습 니 다)

  <item>
      <title>  title>
      <test id="1">
      <description>  oendescription>
      <address>  address>
  item>
   2.json:             ,                 ,              ,JSON        ,           。     JSON           。

XML 의 가 독성 이 좋 고 JSON 의 생 성 데이터 성 (json encode (배열) 전송 속도 가 좋 습 니 다.
5. APP 인터페이스 에서 하 는 일: 데이터 가 져 오기: 데이터베이스 나 캐 시 에서 데 이 터 를 가 져 온 다음 에 인터페이스 데 이 터 를 통 해 클 라 이언 트 에 게 데 이 터 를 제출 합 니 다. 인 터 페 이 스 를 통 해 서버 에 데 이 터 를 제출 한 다음 에 서버 를 통 해 입고 처리 하거나 다른 처 리 를 합 니 다.
6. JSON 방식 패 키 징 통신 인터페이스 PHP 생 성 json 데이터: jsonencode($arr); 설명: 이 함 수 는 UTF - 8 인 코딩 데이터 만 받 을 수 있 습 니 다. 다른 형식의 데 이 터 를 전달 하면 null 통신 데이터 레이 블 형식 을 되 돌려 줍 니 다. code 상태 코드 (200400 등) message 알림 정보 (메 일 형식 이 정확 하지 않 음, 데이터 되 돌려 성공 등)data 는 해당 하 는 데 이 터 를 되 돌려 줍 니 다. - - - JSON code: 200 message: "데이터 반환 성공" - data id: 1 name: "테스트" 인 스 턴 스:
    server :
    public  function json($code,$message = '',$data = array())
    {
            if (!is_numeric($code)){
                return '  ';
            }
             $result = array(
                'code' => $code,
                'message' => $message,
                'data' => $data
        );
        echo json_encode($result);
        exit;
       }

어떤 컨트롤 러:
    public function jsonsAction()
           {
               $arr = array(
                   'id' => 1,
                   'name' => 'jiang'
              );
            $k = wei()->zhwCategory()->json(200,'   ',$arr);
            return $k;
            }

브 라 우 저:http://127.0.0.1/admin/zhw-categorys/jsons
{"code":200,"message":"\u6210\u529f\u54af","data":{"id":1,"name":"jiang"}}


7. PHP XML 데이터 생 성: 7.1 PHP XML 데이터 생 성 1. 조립 문자열 2. 시스템 클래스 사용: DomDocument XML Writer Simple XML 예: DomDocument:
     
                     $dom = new DomDocument('1.0','utf-8');
                     $element = $dom->createElement('test','This id root element');
                     $dom->appendChild($element);
                     echo $dom->saveXML();
              ?>
          ====>  :
           
           <test>This is the root elementtest>
    public static function xml()
            {
                  header("Content-Type:text/html");
                  $xml = "
"
; $xml .= "
"
; $xml .= "200
"
; $xml .= "
"
; $xml .= "
"
; $xml .="1
"
; $xml .="
"
; $xml .="
"
; $xml .=""; echo $xml; }
  7.2  XML    :
              :xmlEncode($code,$message='',$data = array());
         data    :
                 1.array('index' => 'api');
                 2.array(1,7.89);
          :
            server   :
    public 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 .= "
"
; $xml .=self::xmlToEncode($result); $xml .=""; echo $xml; }
        //      
    public function xmlToEncode($data){
               $xml = $attr ="";
               foreach ($data as $key=>$value){
               if(is_numeric($key)){
                   $attr = "id='{$key}'";
                   $key = "item";
               }
               $xml .= "";  //  {$key} {$attr}         
               $xml .=is_array($value) ? self::xmlToEncode($value):$value;
               $xml .="{$key}>
"
; } return $xml; }
  Controller:
     public function xmlsAction()
        {
            $arr = array(
               'id' => 1,
               'name' => 'jiang',
               'type' =>array(4,5,6),
               'test' =>array(1,45,67=>array(1,2,3)),
            );
           $k = wei()->zhwCategory()->xmlEncode(200,'   ',$arr);
           return $k;
         }

8. 종합 방식 으로 통신 데 이 터 를 밀봉 하 는 방법:
       :show($code,$message,$data=array(),$type='json/xml')

최종 페이지: server:


namespace Miaoxing\Zhw\Service;

use miaoxing\plugin\BaseModel;

class ZhwCategory extends BaseModel
{
    const JSON = "json";
    /**
     *  x          
     * @param integer $code    
     * @param string $message     
     * @param array $data   
     * @param string $type     
     * return string
     */
    public function show($code,$message='',$data=array(),$type = self::JSON)
    {
        if (!is_numeric($code)){
            return "    ";
        }
        $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
        }
    }
    /**
     *  json        
     * @param integer $code    
     * @param string $message     
     * @param array $data   
     * return string
     */
    public  function json($code,$message = '',$data = array())
    {
        if (!is_numeric($code)){
            return '  ';
        }
        $result = array(
            'code' => $code,
            'message' => $message,
            'data' => $data
        );
        echo json_encode($result);
        exit;
    }
    /**
     *  xml        
     * @param integer $code    
     * @param string $message     
     * @param array $data   
     * return string
     */
    public 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 .= "
"
; $xml .=self::xmlToEncode($result); $xml .=""; echo $xml; } // public function xmlToEncode($data){ $xml = $attr =""; foreach ($data as $key=>$value){ if(is_numeric($key)){ $attr = "id='{$key}'"; $key = "item"; } $xml .= ""; $xml .=is_array($value) ? self::xmlToEncode($value):$value; $xml .="{$key}>
"
; } return $xml; } }

Controller:
public function jsonsAction()
    {
        $arr = array(
            'id' => 1,
            'name' => 'jiang'
        );
        $k = wei()->zhwCategory()->json(200,'   ',$arr);
        return $k;
    }
    public function xmlsAction()
    {
        $arr = array(
            'id' => 1,
            'name' => 'jiang',
            'type' =>array(4,5,6),
            'test' =>array(1,45,67=>array(1,2,3)),
        );
        $k = wei()->zhwCategory()->xmlEncode(200,'   ',$arr);
        return $k;
    }
    public function showAction()
    {
        $arr = array(
            'id' => 1,
            'name' => 'jiang',
            'type' =>array(4,5,6),
            'test' =>array(1,45,67=>array(1,2,3)),
        );
        $k = wei()->zhwCategory()->show(200,'   ',$arr,'json');
        return $k;
    }

좋은 웹페이지 즐겨찾기