1. Go to this page and download the library: Download polidog/relayer library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
use Polidog\Relayer\Router\Document\HtmlDocument;
$router = Relayer::boot(__DIR__ . '/..');
$router->setDocument(HtmlDocument::create()->loadClientScriptOnlyWithDefer());
$router->run();
// trap: bakes "" if API_TOKEN is unset at compile time
$container->setParameter('app.api_token', $_ENV['API_TOKEN'] ?? '');
// resolves at boot, not at compile — runtime-injected secrets work
$container->setParameter('app.api_token', '%env(API_TOKEN)%');
// src/Pages/users/[id]/page.psx
declare(strict_types=1);
namespace App\Pages\Users;
use App\Service\UserRepository;
use Polidog\Rosanna\Runtime\Element;
use Polidog\Relayer\Router\Component\PageComponent;
final class UserDetailPage extends PageComponent
{
public function __construct(private readonly UserRepository $users) {}
public function render(): Element
{
$user = $this->users->find($this->getParam('id'));
return <h1>{$user->name}</h1>;
}
}
// src/Pages/error.psx — class-style
final class ErrorPage extends ErrorPageComponent
{
public function render(): Element
{
return <h1>{(string) $this->getStatusCode()}: {$this->getMessage()}</h1>;
}
}
return function (PageContext $ctx) use ($posts): Closure {
$post = $posts->find($ctx->params['id']) ?? $ctx->notFound();
if ($post->isDraft && null === $ctx->user()) {
$ctx->abort(403);
}
return fn (): Element => <article>{$post->title}</article>;
};
// src/Pages/api/users/route.php
declare(strict_types=1);
use App\Service\UserRepository;
use Polidog\Relayer\Http\Request;
use Polidog\Relayer\Http\Response;
return [
'GET' => fn (UserRepository $users): Response => Response::json(['users' => $users->all()]),
'POST' => function (Request $req, UserRepository $users): Response {
$users->create($req->allPost());
return Response::json(['ok' => true], 201);
},
];
return Response::redirect('/admin')
->withCookie('staff', '1', ['expires' => new DateTimeImmutable('+1 year')]);
return function (PageContext $ctx): Closure {
$ctx->js('/assets/chart.js', defer: true);
return fn (): Element => <canvas id="chart"></canvas>;
};
final class Dashboard extends LayoutComponent
{
public function render(): Element
{
$this->addJs('/assets/dashboard.js', module: true);
return <div>{$this->getChildren()}</div>;
}
}
// src/Pages/middleware.php
declare(strict_types=1);
use Polidog\Relayer\Http\Request;
return function (Request $request, Closure $next): void {
if (null === $request->header('x-api-key')) {
\http_response_code(401);
echo '{"error":"missing api key"}';
return; // route never runs
}
$next($request);
};
// src/Pages/middleware.php
use Polidog\Relayer\Http\Cors;
return Cors::middleware([
'origins' => ['https://app.example.com'], // or ['*']
// methods / headers / credentials / maxAge are optional
]);
// public/index.php
use Polidog\Relayer\Http\OriginGuard;
use Polidog\Relayer\Relayer;
use Psr\Log\LoggerInterface;
Relayer::boot(__DIR__ . '/..')
->setGuard(OriginGuard::middleware([
'header' => 'X-Origin-Secret', // default
'secretsFromEnv' => ['ORIGIN_SECRET', 'ORIGIN_SECRET_PREVIOUS'],
'except' => ['/healthz'], // exact path, or `/prefix/*`
'mode' => 'enforce', // or 'report'
'logger' => Relayer::container()->get(LoggerInterface::class), // optional
]))
->run();
use Polidog\Relayer\Http\TrustedProxy;
// Cloudflare in front: CF-Connecting-IP, honored only from Cloudflare's ranges.
// The ranges are not bundled (they change) — fetch https://www.cloudflare.com/ips-v4
// and /ips-v6 and pass them in.
TrustedProxy::middleware(['preset' => 'cloudflare', 'proxies' => $cloudflareRanges]);
// Fly.io: Fly-Client-IP, honored only from Fly's private network (6PN).
TrustedProxy::middleware(['preset' => 'fly', 'proxies' => ['fdaa::/16']]);
// A proxy of your own: X-Forwarded-For walked from the right past your proxies.
TrustedProxy::middleware(['preset' => 'xff', 'proxies' => ['10.0.0.0/8']]);
// Any other single-IP header (`preset` and `header` are mutually exclusive).
TrustedProxy::middleware(['header' => 'X-Real-IP', 'proxies' => ['192.0.2.1']]);
use Polidog\Relayer\Router\RedirectException;
public function render(): Element
{
return (
<form action={$this->action([$this, 'save'])}>
<input name="title" />
<button>save</button>
</form>
);
}
public function save(array $form): void
{
// ... handle $form['title']
throw new RedirectException('/dashboard'); // 303 Post/Redirect/Get
}
// src/Pages/users/page.psx
declare(strict_types=1);
use App\Service\UserRepository;
use Polidog\Relayer\Router\Component\PageContext;
use Polidog\Rosanna\Runtime\Element;
return function (PageContext $ctx, UserRepository $users): Closure {
$save = $ctx->action('save', function (array $form) use ($users, $ctx): void {
$users->create($form['name']);
$ctx->redirect('/users'); // 303 Post/Redirect/Get; unwinds here
});
return function () use ($save, $users): Element {
return (
<main>
<ul>{\array_map(fn($u) => <li>{$u->name}</li>, $users->all())}</ul>
<form action={$save}>
<input name="name" />
<button>save</button>
</form>
</main>
);
};
};
final class ContactForm implements Renderable
{
private array $errors = [];
public function __construct(private readonly string $title) {}
public function render(): Element
{
$send = PageContext::current()->action('send', function (array $form): void {
$result = Validator::object([/* ... */])->safeParse($form);
if (!$result->success) {
$this->errors = $result->errors; // shown in the response
}
});
return <form action={$send}>{/* $this->title, $this->errors ... */}</form>;
}
}
// list → positional: handler($form, 42)
$delete = $ctx->action('delete', function (array $form, int $id) use ($repo): void {
$repo->delete($id);
}, [$user->id]);
// assoc → named args: handler(formData: $form, id: 42)
$ctx->action('delete', fn (array $formData, int $id) => $repo->delete($id), ['id' => $user->id]);
return function (PageContext $ctx) use ($schema): Closure {
$errors = [];
$save = $ctx->action('save', function (array $form) use ($schema, &$errors, $ctx): void {
$result = $schema->safeParse($form);
if (!$result->success) { $errors = $result->errors; return; }
// ... on success: $ctx->redirect('/users') (303 Post/Redirect/Get)
});
// $errors is mutated after the action runs → capture by reference
return function () use ($save, &$errors): Element { /* render $errors */ };
};
// src/PagesConfigurator.php
declare(strict_types=1);
namespace App;
use App\Service\UserRepository;
use App\Service\PdoUserRepository;
use Polidog\Relayer\AppConfigurator as BaseConfigurator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
final class AppConfigurator extends BaseConfigurator
{
public function configure(ContainerBuilder $container): void
{
$container->register(PdoUserRepository::class);
$container->setAlias(UserRepository::class, PdoUserRepository::class)
->setPublic(true);
}
}
Relayer::boot(__DIR__ . '/..', new App\AppConfigurator(__DIR__ . '/..'))->run();
// src/Components/TodoList.psx
declare(strict_types=1);
namespace App\Components;
use Polidog\Relayer\Db\Database;
use Polidog\Relayer\Relayer;
use Polidog\Rosanna\Runtime\Element;
return function (array $props): Element {
$db = Relayer::container()->get(Database::class);
$todos = $db->fetchAll('SELECT id, title, done FROM todos ORDER BY id');
return (
<ul>
{array_map(fn($t) => <li>{$t['title']}</li>, $todos)}
</ul>
);
};
// src/Pages/users/page.psx
declare(strict_types=1);
namespace App\Pages\Users;
use App\Service\UserRepository;
use Polidog\Rosanna\Runtime\Element;
use Polidog\Relayer\Router\Component\PageComponent;
final class UsersPage extends PageComponent
{
public function __construct(private readonly UserRepository $users)
{
}
public function render(): Element
{
$users = $this->users->all();
// ...
}
}
// src/Pages/signup/page.psx
declare(strict_types=1);
use Polidog\Relayer\Http\Request;
use Polidog\Relayer\Router\Component\PageContext;
use Polidog\Rosanna\Runtime\Element;
return function (PageContext $ctx, Request $req): Closure {
$errors = [];
if ($req->isPost()) {
$email = $req->post('email') ?? '';
if (!\filter_var($email, \FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Invalid email';
}
if ([] === $errors) {
$ctx->redirect('/thanks'); // 303 Post/Redirect/Get; unwinds here
}
}
return function () use ($errors, $req): Element {
// ... render form, echoing $req->post('email') back into the input
};
};
// src/Components/UserHeader.psx — no session_start(), no $_SESSION
return function (array $props, Authenticator $auth): Element {
$name = $auth->user()?->displayName;
…
};
#[Auth(redirectTo: '')] // 401 for an absent/bad token (no redirect)
final class ApiEndpoint extends PageComponent { /* ... */ }
#[Auth(roles: ['admin'])] // roles read from the token's claims
final class AdminApi extends PageComponent { /* ... */ }
// src/Pages/auth/token/route.php — POST { } with Authorization: Bearer <jwt>
declare(strict_types=1);
use Polidog\Relayer\Auth\Authenticator;
use Polidog\Relayer\Auth\Token\BearerToken;
use Polidog\Relayer\Auth\Token\TokenVerifier;
use Polidog\Relayer\Auth\Token\AuthorizationHeader;
use Polidog\Relayer\Http\Response;
return [
'POST' => static function (
TokenVerifier $verifier,
Authenticator $auth,
AuthorizationHeader $header,
): Response {
$identity = $verifier->verify(
BearerToken::parse($header->value()) ?? '',
);
if (null === $identity) {
return Response::json(['error' => 'invalid token'], 401);
}
$auth->login($identity); // rotates the session id
return Response::json(['user' => $identity->toArray()]);
},
];
// src/Pages/page.psx
declare(strict_types=1);
namespace App\Pages;
use Polidog\Relayer\Router\Component\PageComponent;
use Polidog\Relayer\Http\Cache;
use Polidog\Rosanna\Runtime\Element;
#[Cache(
maxAge: 3600,
sMaxAge: 86400,
public: true,
vary: ['Accept-Language'],
etag: 'home-v1',
)]
final class HomePage extends PageComponent
{
public function render(): Element { /* ... */ }
}
// src/Pages/feed/page.psx
declare(strict_types=1);
use Polidog\Relayer\Http\Cache;
use Polidog\Relayer\Router\Component\PageContext;
use Polidog\Rosanna\Runtime\Element;
return function (PageContext $ctx): Closure {
// Lightweight setup: declare cache, read params. NO DB queries here.
$ctx->cache(new Cache(maxAge: 60, public: true, etagKey: 'feed'));
return function () use ($ctx): Element {
// Heavy work goes here — only runs on cache miss.
// ... query DB, build the page
};
};
#[Cache(maxAge: 60, public: true, etagKey: 'user-list')]
final class UsersPage extends PageComponent { /* ... */ }
final class UserRepository
{
public function __construct(private readonly EtagStore $etags) {}
public function save(User $user): void
{
// ... persist
$this->etags->set('user-list', \sha1((string) \microtime(true)));
}
}
final class RedisEtagStore implements EtagStore
{
public function __construct(
private readonly \Redis $redis,
private readonly string $prefix = 'etag:',
) {}
public function get(string $key): ?string
{
$value = $this->redis->get($this->prefix . $key);
return \is_string($value) && $value !== '' ? $value : null;
}
public function set(string $key, string $etag): void
{
$this->redis->set($this->prefix . $key, $etag);
}
public function forget(string $key): void
{
$this->redis->del($this->prefix . $key);
}
}
use Polidog\Relayer\Db\Database;
final class UserPage extends PageComponent
{
public function __construct(private readonly Database $db) {}
public function render(): string
{
$user = $this->db->fetchOne(
'SELECT id, name FROM users WHERE id = :id',
['id' => 42],
);
// ...
}
}
$db->transactional(function (Database $tx): void {
$tx->perform('INSERT INTO orders (user_id) VALUES (?)', [$userId]);
$tx->perform('UPDATE users SET order_count = order_count + 1 WHERE id = ?', [$userId]);
});
use Polidog\Relayer\Http\Client\HttpClient;
final class WeatherPage extends PageComponent
{
public function __construct(private readonly HttpClient $http) {}
public function render(): string
{
$res = $this->http->get('https://api.example.com/weather?city=tokyo', [
'Accept' => 'application/json',
]);
if (!$res->ok()) {
// 4xx/5xx is not an exception — a normal HttpResponse to branch on
return 'Could not fetch (' . $res->status . ')';
}
$data = $res->json();
// ...
}
}
$schema = Validator::object([
'name' => Validator::string()->trim()->lidator::string()->min(8, 'Password must be at least 8 characters.'),
]);
$signup = $ctx->action('signup', function (array $form) use ($schema, &$errors): void {
$result = $schema->safeParse($form);
if (!$result->success) {
$errors = $result->errors; // hand field errors to the view
return;
}
// $result->data is coerced
});
use Polidog\Relayer\Validation\Judge;
$schema = Validator::object([
'body' => Validator::string()->trim()->min(10)
->satisfies($judge, '`value` is a genuine support question, not spam or ads', 'Looks like spam.', 0.7),
]);
use Psr\Log\LoggerInterface;
final class CheckoutPage extends PageComponent
{
public function __construct(private readonly LoggerInterface $log) {}
public function render(): string
{
$this->log->info('checkout started for {user}', ['user' => $userId]);
// ...
}
}
use Polidog\Relayer\Profiler\Profiler;
public function __construct(private readonly Profiler $profiler) {}
// one-shot event
$this->profiler->collect('app', 'cache warmed', ['keys' => 12]);
// timed span (finalized by stop())
$span = $this->profiler->start('app', 'heavy compute');
$result = $this->compute();
$span->stop(['rows' => \count($result)]);
// timed span around a call, finalized for you (returns the call's value,
// records an `error` payload and rethrows if it throws)
$user = $this->profiler->measure('lib', 'sdk.fetchUser',
fn () => $this->thirdPartySdk->fetchUser($id));
final class TraceableWeatherApi implements WeatherApi
{
public function __construct(
private readonly WeatherApi $inner,
private readonly Profiler $profiler,
) {}
public function forecast(string $city): Forecast
{
// Choose the label/payload deliberately — record the city, not an
// API key the real client might also take.
return $this->profiler->measure('lib', 'weather.forecast',
fn () => $this->inner->forecast($city));
}
}
// config: AppConfigurator::configure()
if ($_ENV['APP_ENV'] === 'dev') {
$container->register(TraceableWeatherApi::class)
->setArguments([new Reference(HttpWeatherApi::class), new Reference(Profiler::class)])
->setPublic(true);
$container->setAlias(WeatherApi::class, TraceableWeatherApi::class)->setPublic(true);
}
use Polidog\Rosanna\Runtime\RequestLifecycle;
RequestLifecycle::onReset(self::class, function (): void {
$this->items = [];
});
your-app/
.env # loaded automatically if present
composer.json
config/
services.yaml # auto-loaded if present (also services.php / .yml)
public/
index.php
src/
Pages/ # AppRouter file-based routes live here
layout.psx
page.psx
about/
page.psx
AppConfigurator.php # your service registrations (extends Polidog\Relayer\AppConfigurator)
METHODS PATH TYPE FILE
GET,POST / page src/Pages/page.psx
GET /api/hello native src/Pages/api/hello/route.go
GET,POST /api/users api src/Pages/api/users/route.php
GET,POST /users/[id] page src/Pages/users/[id]/page.psx
middleware src/Pages/middleware.php (php)
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.