Send
In Phlame, the send function serves as a crucial component for handling API responses. This function allows you to send data to clients in a structured format, with options for customizing the response status, format, and additional headers or footers. Let's delve into the signature and functionality of the send function in Phlame:
Function Signature:
Api::send($data, $key, $status, $format, $header, $footer, $ignoreformat);
Parameters:
$data
: The array of data to be sent in the response.$key
: The key to be used for the data in the final output. Default: 'segments'$status
: The HTTP status code to be included in the response. Default: 200$format
: The format of the response data (e.g., 'json' or 'XML'). Any other format will throw an error if$ignoreformat
is false. Default: json$header
: An optional array of additional headers to be included before the data.$footer
: An optional array of additional data to be included after the main data.$ignoreformat
: A boolean flag indicating whether to ignore the specified format and send the data as is. Default: false
Example Usage (JSON):
// Sending JSON data with a custom key, header, footer, and status code
// Note: Source format must be JSON
$data = Api::segment('out', ['test'=>'data']);
Api::send($data,
key:'response',
status:418,
header: ["loc" => "head"],
footer: ["loc" => "foot"],
format:'json'
);
Api Output (JSON)
{
"header": {
"loc": "head"
},
"response": {
"out": {
"test": "data"
}
},
"footer": {
"loc": "foot"
}
}
Example Usage (XML):
// Sending XML data with a custom key, header, footer, and status code
// Note: Source format must be XML
$data = Api::segment('out', ['test'=>'data']);
Api::send($data,
key:'response',
status:418,
header: ["loc" => "head"],
footer: ["loc" => "foot"],
format:'xml'
);
Api Output (XML)
<root>
<header>
<loc>head</loc>
</header>
<response>
<out>
<test>failed</test>
</out>
</response>
<footer>
<loc>foot</loc>
</footer>
</root>
Functionality:
- The
send
function allows you to send data to clients in a structured format, such as JSON or XML. - You can customize the response status code, format, and other aspects of the response.
- The
$data
parameter represents the main content of the response. - You can specify a custom key (
$key
) to be used for the data in the final output. - Additional headers (
$header
) and footer data ($footer
) can be included before and after the main data, respectively. - The
$ignoreformat
parameter determines whether to ignore the specified format and send the data as is.
tip
You can use the function Api::sendraw()
to send raw data [no formatting] with just status code and data.
Example:
Api::sendraw($data, status: 200);
status is null by default in sendraw