iT邦幫忙

2019 iT 邦幫忙鐵人賽

DAY 18
0
Modern Web

你說Codeigniter還能怎麼做?系列 第 18

[Day18] 改造API Part3

上次我們已經把API管理化,今天就會依照路由規則來分別建造不同的API資料夾

創建API Models

昨天我們透過routes_api.php來管理API路徑如下:

  $config['routes_api'] = array(
    'user'=> array(
      'get_user'=> 'get_user'
    )
  );

接著我們會依照不同的類別來建立不同的檔案,如上方的user,主要是關於用戶的API,藉由規則來達到管理的成效~首先我們先在Models新增一個API的資料夾,之後我們會透過這個資料夾來管理各種API,接著我們新增一個User.php的Models,如Models/API/User.php

<?php if (!defined('BASEPATH')) { exit('No direct script access allowed'); }

class User extends CI_Model {
  public function __construct() {
    parent::__construct();
    // 語系設定
    $this->language = $this->mod_config->getLanguage();
  }
}

?>

接著我們在裡面新增一個get_user的函式:

  function get_user() {
    
  }

設定測試API

下一步我們回到controllers/Api.php修改內容:

  function authenticate($path_name, $func_name) {
    // 驗證設定檔是否有符合規則
    $auth = $this->check_api_file($path_name, $func_name);
    // 確認回傳是可用的API
    if ($auth['sys_code'] == 200) {
      // 載入API Model
      $this->load->model('API/'.ucfirst($auth['path']), $auth['path']);
      // 如果發現是圖片或是檔案,也把他丟進來
      $get_post_image_data = array();
      $get_post_image_data = array_merge($get_post_image_data, $this->get_post_data());
      $get_post_image_data = array_merge($get_post_image_data, $_FILES);
      // 接著使用此API並把結果回傳輸出出去
      $response = $this->$auth['path']->$auth['func']($get_post_image_data);
      header('Content-type:text/json');
      echo json_encode($response, JSON_UNESCAPED_UNICODE);
    }
  }}
    
  // 取得傳輸進來的資料
  function get_post_data() {
    $getData = $this->input->get();
    $postData = $this->input->post();
    return array_merge($getData, $postData);
  }

上方就是透過加載不同的API Models來操作不同的內容,並且透過$get_post_image_data,來取得傳輸進來的資料,接著在傳送到我們所指定的API路徑,接著透過回傳的資料來去顯示。

下一步我們回到Models/API/User.php來修改get_user函式:

  function get_user($getpostData) {
    $json_arr['response'] = $getpostData;
    $json_arr = $this->mod_config->msgResponse((isset($json_arr))?$json_arr:array(), 'success', 'PROCESS_SUCCESS', $this->language);
    // 最後回傳資料
    return $json_arr;
  }

接著我們就能在get_user拿到傳接進來的資料,接著最後我們在回傳回到controllers讓他顯示給用戶端。
設定API

下一步我們來透過網址測試:
http://ip-address/api/user/get_user?name=David
測試網址

如此一來就完成了!接著明天我們來試點小東西。

Next station ... 改造API Part4


上一篇
[Day17] 改造API Part2
下一篇
[Day19] 改造API Part4
系列文
你說Codeigniter還能怎麼做?30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言