I'm creating a REST API using FuelPHP and its ORM, docs found here: http://fuelphp.com/docs/packages/orm/crud.html
I can return a object of the database row like so:
$entry = Model_V1_Inventory::find(1);
This returns me the object where the PK is equal to 1, which is as expected. How do I access the _data array to json_encode it and return it as part of the REST response? I can access individual items in the array by simply calling:
$entry->product_ref
As an example but I can't see anyway of returning the _data array with it being protected.
The returned objected from the 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
(
)
)
Ok after some playing I found a fix for this with one of FuelPHP's built in classes, Format;
Format::forge($entry)->to_array();
Will carry out the conversion and then json_encode the array for the response. Here is my full method for sending a json encoded string back to the user using the 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);
}
}