problem with response and entity |
How do you do guys ? nice ? ok 'cause I have a problem
if my model return and object Entity, If i ask in my controller the typeof $entity->createdAt, it answer CodeIgniter\I18n\Time Object ok nice (magical mutations and casts works) BUT.... if i do $this->response->SetJson($entity); i got an empty object. no cast, no magical conversions, all fields are protected so the json_encode can't access to this fields. The same with a var_dump or print_r. fields are not converted. How can i send over a REST application the correct representation of my entity ? Note : If i put some fields"public" in my entity, i can see it in my response but without magical conversion... is that a bug or a workaround ? maybe someone did this trick ? the worst is that if i do $this->response->SetJson($entity->created_at); I've got an error 500 about a problem with format. Code: Argument 1 passed to CodeIgniter\Format\JSONFormatter::format() must be of the type array, object given, called in /www/api/system/HTTP/Response.php on line 551
Have you tried "return $this->respond($myentity);"? if $myentity is an associative array, it should be returned as JSON.
If it isn't an array, you could cast it as such, or use the Model's asArray() method as part of the chain when you retrieve the entity.
Is this meant to be a resource controller, eg an API endpoint?
If so, I recommend using the API response trait, which is where that method comes from. See https://github.com/codeigniter4/CodeIgni...roller.php This is a work-in-progress.
my bad, bad use of ResponseTrait.
return $this->respond($users_data, 200); -> <response/>
well... that the same
Code: [ PHP Code: <?php i will try to make a custom entity and a sort of toString() or toJson() method who will read the protected vars and reconstruct a correct object. a json_encode() si not enough for that kind of object.
yeepee !!!!
Code: [ so basically, i wrote a toArray() method PHP Code: public function toArray(){ and VOILA ! so i will wrote MY_Entity with many converters json, xml, yaml maybe .... and my own MY_Model who will call my converters after find. and maybe something like that. And I saw that call inside a model $this->created_at is not the same as $this->__get('created_at'). Is that the normal behavior ? |
Welcome Guest, Not a member yet? Register Sign In |