I'm having some problems with deciding where to set the content-type header in a vanilla mvc framework. Should i add it inside the controllers method:

class ApiController extends Controller{

    public static function v1(){
        header('Content-Type: application/json');
        //some logic to output some json
    }    

} 

My mvc works more like an mvp:

Model <--> Controller <--> View
有帮助吗?

解决方案

As talking about content-type headers only makes sense in the context of a remotely rendered view, as it typical for web-applications, I will assume that is the case here as well.

The content-type header, as well as other headers, are part of the communication mechanism for transferring the View information from the back-end part to the front-end (view rendering) part of the application.

The communication mechanism is an application concern and not a business logic concern, because it would change when you use different technologies to build the application. This means that it definitely does not belong in the Model part.

If setting the header should be part of the Controller or the View/Presenter depends mostly on the MVC/MVP framework that you use. In most frameworks for web applications, all communication with the front-end is handled by the Controller part and the View part only does a transformation of the Model data into a format that the front-end or browser can understand. With these frameworks, setting the content-type header would be a responsibility of the Controller. Other frameworks could work differently and have more communication logic in the View part and then it might be more straightforward to set the header in the View.

许可以下: CC-BY-SA归因
scroll top