3

In-Template Response Building

 1 year ago
source link: http://paul-m-jones.com/post/2022/09/23/in-template-response-building/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

In-Template Response Building

I am fond of saying that in server-side applications, the Template is not the View. Instead, the HTTP Response is the View. That is, the Response presented by the server is not only the templated content; the presentation includes both the headers and the content in the Response.

But what if you can build the HTTP Response inside a Template?

That is just what the new Qiq helpers using Sapien, let you do. Using the qiq/helper-sapien package, you can set Response headers, cookies, etc. from inside your template code ...

{{ response()->setVersion('1.1') }}
{{ response()->setCode(200) }}
{{ response()->setHeader('content-type', 'text/plain') }}
Hello, world!

... and get back a complete Response object for sending:

$response = $template->response()->render($template);
$response->send();

In addition, you can use setFile() to build a file-download Response ...

{{ response()->setFile('/path/to/file.txt') }}

... or setJson() to build a JSON Response:

{{ response()->setJson(['foo' => 'bar']) }}

Does this mean the Template is the View after all? If so, it's only because the entire Response is built by the Template. Perhaps this could be called a ResponseView.

Will this make a Qiq template into a complete ADR Responder? Maybe, maybe not -- but it does mean that Responder implementations have the option to hand off most or all Response-building work to Qiq template code.

Are you stuck with a legacy PHP application? You should buy my book because it gives you a step-by-step guide to improving you codebase, all while keeping it running the whole time.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK