fractal
fractal copied to clipboard
Allow at least stdClass objects as the return values from transformers
Right now, I'm forced to return an array from my transformer, no matter how hard I try to override classes in Fractal (there's no interface for serializers and the base class required everywhere in Fractal type-hints the arguments to array
).
This is unfortunate because my API sometimes has objects that are -- when transformed -- an empty JSON object. But with Fractal, I'm forced to output []
instead of {}
. While this is harmless in PHP by nature, this can be an issue in other languages.
It's also highly confusing when using embedding and doing sth like /thing?embed=child
(so I'm embedding a single item that can be empty) and my JSON now reads
{
"id": "thingID",
"child": {
"data": [ ]
}
}
which implies that data
normally is an array, even though when there is a child, the JSON looks like
{
"id": "thingID",
"child": {
"data": {
"id": "childID"
}
}
}
Also, just for aesthetic reasons, it would be nice to at least be able to return an new stdClass();
and get an empty object in my JSON.
I think you raise a valid point here, I'll look into this tonight and see if I can get something done this week!
On first look it appears that this might be more tricky than first seems. converting the data to JSON first calls toArray
which is why empty data is parsed as an array.
The only way around this is to refactor the toJson
method which I am looking at now!
+1
+1
+1
+1
Should be able to output null
at least
+1
You can get around this by using a Collection instead of a Item.
any solution from this, i have the same issue here
+1
any solution from this?
To have an empty object in your output you need to not return anything in your transformer method.
For example:
Imagine you have this in your constructor: $this->defaultIncludes = [ 'data' ];
And this in your transformer: return ["id" => $this->getId(), "data" => (object)[]]
And the method:
public function includeData() {
if ($condition === true) {
return $this->item($data, new DataTransformer());
} // ----> Here if condition is not met your data would be empty and return value is going to be void or null.
This will result in empty object in your JSON as you expected.
Or just pass null
in the transformer; Like this:
return ["id" => $this->getId(), "data" => null]
Hey @snaderiBC - is it the only solution now as well? Is there any other option available? Thanks in advance.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed after 4 weeks if no further activity occurs. Thank you for your contributions.