簡體   English   中英

使用FuelPHP從ORM返回_data數組

[英]Return _data array from ORM with FuelPHP

我正在使用FuelPHP及其ORM創建REST API,文檔可在此處找到: http ://fuelphp.com/docs/packages/orm/crud.html

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

$entry = Model_V1_Inventory::find(1);

這使我返回了PK等於1的對象,這與預期的一樣。 如何訪問_data數組以json_encode並將其作為REST響應的一部分返回? 我可以通過簡單地調用以下命令來訪問數組中的單個項目:

$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
        (
        )

)

好了,在玩了一些游戲之后,我發現使用FuelPHP的一個內置類Format來解決此問題。

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

將執行轉換,然后對響應數組進行json_encode編碼。 這是我使用FuelPHP ORM將json編碼的字符串發送回用戶的完整方法:

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);
    }
}

您也可以簡單地使用$entry->to_array() ,不需要Format類。

https://github.com/fuel/orm/blob/fc4f27af2cc55e99c435d490d0af69fabda70cb7/classes/model.php#L2028

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM