Return 来自 ORM 和 FuelPHP 的 _data 数组

Return _data array from ORM with FuelPHP

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

我可以 return 数据库行的对象,如下所示:

$entry = Model_V1_Inventory::find(1);

这个return是我PK等于1的对象,符合预期。如何访问 _data 数组以 json_encode 它和 return 它作为 REST 响应的一部分?我可以通过简单地调用访问数组中的单个项目:

$entry->product_ref

举个例子,但我无论如何都看不到 returning _data 数组受到保护。

returned 反对 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::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 class。

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