R
R
Roman2017-10-11 19:36:41
Yii
Roman, 2017-10-11 19:36:41

Why is the ContentNegotiator filter needed in Yii2?

The purpose of this filter is not entirely clear.
The documentation says:
ContentNegotiator supports negotiation of response format and application language. It tries to determine the response format and/or language by checking the GET parameters and the Accept HTTP header.

  • i.e. it, depending on the contents of the Accept and Accept-Language headers, determines whether to execute the action?
  • or allows you to use some data to independently choose the response format in the action?
  • And what's with the GET parameter? isn't the HTTP header enough?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mitaichik, 2017-10-12
@kublahanov

Here is the documentation https://github.com/yiisoft/yii2/blob/master/docs/g...
The main purpose is to return the response in the correct format.
In the Accept header, the client indicates in what format he needs the data, for example, json or xml.
From the action, you can return not only a string, but a model, an array (including models), a data provider, etc.
The ContentNegotiator converts this data to the required format - for example, it serializes the model to json, sets the headers, etc. Serialization rules can be described in the model, or you can implement your own serializer (in the documentation, alas, this is scattered in different places). In general, to create an api - a necessary thing.

M
matperez, 2017-10-11
@matperez

Well, yes, you answered yourself.
Look at the code . There, in principle, it is clear that the language and format of the response can be transmitted both through headers and through the GET parameters _lang and _format.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question