2015/05/02

在Google App Engine(GAE) 使用 firebase REST API

本想用firebase當作GAE的DB的
但是讀取速度有點慘...
好在資料量不大,所以改用gae的memcache
寫都寫了做個紀錄

溫馨提示:
由於GAE不能用curl,所以要用GAE自己的URL Fetch
需要使用file_get_contents with stream_context


function firebase($url, $data=null, $method='GET'){
 $method = strtoupper($method);
 $context = [
  'http' => [
   'method' => $method
  ]
 ];

 if($method != 'GET' && $method != 'DELETE' && !is_null($data)){
  $content = json_encode($data);
  $header = "Content-Type: application/json\r\n".
      "Content-Length: ".strlen($content)."\r\n";
  $context['http']['header'] = $header;
  $context['http']['content'] = $content;
 }

 $context = stream_context_create($context);
 $result = file_get_contents($url, false, $context);
 return $result;
}

Sample:
$url = "https://example.firebaseio.com/somedata.json";

//取得資料
$res = firebase($url);  //$res 是json text

//送出資料
$data = array('a'=>123, 'b'=>456);
$res = firebase($url, $data, 'PUT');

PATCH跟POST沒試過,但是應該也可以動啦XDD


firebase REST API: https://www.firebase.com/docs/rest/guide/saving-data.html
Google App Engine Url Fetch: https://cloud.google.com/appengine/docs/php/urlfetch/

沒有留言:

張貼留言