使用FuelPHP从ORM返回_data数组

时间:2016-04-26 13:57:06

标签: php rest orm 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数组被保护。

退回的反对意见:

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

)

2 个答案:

答案 0 :(得分:0)

好好玩了一段时间后,我找到了一个修复,使用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);
    }
}

答案 1 :(得分:0)

您也可以使用$entry->to_array(),不需要Format课程。

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