Serve any type of file
In the page declaration, only specify the class name, and headers if needed:
<?php
$config = [
'acme' => [
Core_Page::TYPE => [
/* ... */
'/api/customers/' => [
'class' => Acme_Page_Api_Customer::class,
'_headers' => [
'Content-Type' => 'application/json',
],
],
/* ... */
],
],
];
In the class, cancel any potential template, then render the desired content:
<?php
declare(strict_types=1);
class Acme_Page_Api_Customer extends Core_Page
{
public function execute(): void
{
$this->setTemplate(null);
}
public function render(): string
{
return json_encode(
[
'customers' => [
[
'identifier' => 1,
'name' => 'John Doe',
],
],
]
);
}
}
Examples
sitemap.xml
<?php
$config = [
'acme' => [
Core_Page::TYPE => [
/* ... */
'/sitemap.xml' => [
'class' => Acme_Page_Sitemap::class,
'_headers' => [
'Content-Type' => 'application/xml',
],
],
/* ... */
],
],
];
<?php
declare(strict_types=1);
class Acme_Page_Sitemap extends Core_Page
{
public function execute(): void
{
$this->setTemplate(null);
}
public function render(): string
{
$pages = App::db()->getAll('pages');
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
foreach ($pages as $page) {
$xml .= '<url><loc>' . $this->getBaseUrl($page['slug']) . '</loc></url>' . "\n";
}
$xml .= '</urlset>';
return $xml;
}
}
robots.txt
<?php
$config = [
'acme' => [
Core_Page::TYPE => [
/* ... */
'/sitemap.xml' => [
'class' => Acme_Page_Robots::class,
'_headers' => [
'Content-Type' => 'text/plain',
],
],
/* ... */
],
],
];
<?php
declare(strict_types=1);
class Acme_Page_Robots extends Core_Page
{
public function execute(): void
{
$this->setTemplate(null);
}
public function render(): string
{
$robots = 'User-agent: *' . "\n";
if (App::getEnvironment() === 'default' {
$robots .= 'Allow: /' . "\n";
} else {
$robots .= 'Disallow: /' . "\n";
}
return $robots;
}
}