B
B
Bogdan Khvalko2020-12-11 23:52:47
Yii
Bogdan Khvalko, 2020-12-11 23:52:47

How to customize the display of YII2 API fields?

Yes, I know that the REST API architecture is implemented in yii2, but the guys who work with me didn’t like it, they wanted specific data to be given for a specific request, and there was no need to add any conditions)

There is a "user" model with the fields name, age , token.
And the "security" model with the fields time, status, hash.
When requesting site/api/user, you need to show {"name":'Tolik', "age":28} token no.
And when requesting site/api/security {"status":true, "hash":'asdas5asd5asd', "token":'asdasd548wqf4as4f5'}

If I hide it in user->fields() I won't be able to display the token at site/api/security .
And there are a lot of such intertwined models and properties. How can I elegantly get around this?

Right now I'm pulling out the data from the "security" model, putting it in $data['security'] = $security
Then I get the "user" model and $data['token'] = $user->token.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
toratoda, 2020-12-20
@quitting

You can create a Response class that implements the JsonSerializable interface. In an interface method, collect the properties of the current class and return them as an array. In the constructor, the class will take the user model and set the necessary properties for itself.
So you will have a separate class whose purpose is only to generate a response (you can declare an abstract base class and generate responses for each method), and you can also specify typing for properties. So you will know exactly what will be the output and not rely on an array.

R
Ruslan, 2020-12-13
@Tiasar

Or maybe it's easier to do it through linking models and getters? Would you give me the codes of your models ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question