2016-04-26 44 views
2

我創建使用FuelPHP和ORM,文檔一個REST API這裏找到:http://fuelphp.com/docs/packages/orm/crud.html從ORM返回_data陣列FuelPHP

我可以返回數據庫行的對象,像這樣:

$entry = Model_V1_Inventory::find(1);

這會返回我PK等於1的對象,這與預期的一樣。如何訪問_data數組以將其作爲REST響應的一部分進行json_encode並將其返回?我可以簡單地調用訪問各個項目的數組中:

$entry->product_ref 

作爲一個例子,但我不能看到返回它被保護_data數組的反正。

返回從ORM反對:

Model_V1_Inventory Object 
(
    [_is_new:protected] => 
    [_frozen:protected] => 
    [_sanitization_enabled:protected] => 
    [_data:protected] => Array 
     (
      [product_ref] => from the model 
      [cost_price] => 0.99 
      [rrp_price] => 11.67 
      [current_price] => 5.47 
      [description] => test description 
      [created_at] => 2016-04-26 14:29:20 
      [updated_at] => 2016-04-26 14:29:20 
      [id] => 1 
     ) 

    [_custom_data:protected] => Array 
     (
     ) 

    [_original:protected] => Array 
     (
      [product_ref] => from the model 
      [cost_price] => 0.99 
      [rrp_price] => 11.67 
      [current_price] => 5.47 
      [description] => test description 
      [created_at] => 2016-04-26 14:29:20 
      [updated_at] => 2016-04-26 14:29:20 
      [id] => 1 
     ) 

    [_data_relations:protected] => Array 
     (
     ) 

    [_original_relations:protected] => Array 
     (
     ) 

    [_reset_relations:protected] => Array 
     (
     ) 

    [_disabled_events:protected] => Array 
     (
     ) 

    [_view:protected] => 
    [_iterable:protected] => Array 
     (
     ) 

) 

回答

0

好一些上場之後,我發現這個修復與FuelPHP內置的類別之一,格式;

Format::forge($entry)->to_array(); 

將執行轉換,然後json_encode響應的數組。這裏是我的發送JSON編碼的字符串返回到使用FuelPHP ORM用戶完整的方法:

public function get_product() 
{ 
    $product_id = Uri::segment(4); 
    $response = new Response(); 
    try{ 
     if($product_id == null){ 
      throw new Exception('No product ID given'); 
     }else{ 
      $entry = Model_V1_Inventory::find($product_id); 
      $entry = Format::forge($entry)->to_array(); 

      $response->body(json_encode($entry)); 
      $response->set_status(200); 
      return $response; 
     }     
    }catch(Exception $e){ 
     $response->body(json_encode(['Status' => 400, 'Message' => $e->getMessage()])); 
     $response->set_status(400); 
     return $response; 
     throw new Exception($e); 
    } 
}