PHP code example of karewan / knroute-inertia

1. Go to this page and download the library: Download karewan/knroute-inertia 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/ */

    

karewan / knroute-inertia example snippets


declare(strict_types=1);

use Karewan\KnRoute\Router;
use Karewan\KnRouteInertia\ErrorHandler;
use Karewan\KnRouteInertia\Inertia;
use Karewan\KnRouteInertia\InertiaMiddleware;

session_start();

Inertia::configure(
	rootView: __DIR__ . '/App/Views/app.php',
	version: APP_VERSION,
	share: static fn(): array => [
		'appName' => 'My app',
		'auth' => ['user' => fn() => currentUser()?->toArray()],
	],
);

$router = new Router();
$router->addGlobalMiddleware(new InertiaMiddleware());
$router->setDefaultErrorHandler(new ErrorHandler('Error'));
$router->registerRoutesFromControllers(
	controllersPath: __DIR__ . '/App/Controllers',
	cacheFile: __DIR__ . '/tmp/routes.php',
);
$router->run();

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<script type="module" src="/build/app.js"></script>
	<?= $inertia->head('<title>My app</title>') 

Inertia::configure(
	rootView: static fn(RootView $inertia): string => view('App', ['inertia' => $inertia]),
);

use Karewan\KnRoute\Attributes\Get;
use Karewan\KnRouteInertia\Inertia;

final class EventsController
{
	#[Get('/events/{id:uint}')]
	public function show(int $id): void
	{
		$event = EventsDao::get($id) ?? throw new HttpException(404);

		Inertia::render('Events/Show', [
			'event' => ['id' => $event->id, 'title' => $event->title],
		]);
	}
}

Inertia::render('Dashboard', [
	'auth' => fn() => [
		'user' => currentUser(),
		'notifications' => Inertia::defer(fn() => NotificationsDao::unread()),
	],
	// Nested into "auth" when the page is resolved
	'auth.permissions' => fn() => currentUser()->permissions(),
]);

final class Avatar implements ProvidesInertiaProperty
{
	public function __construct(private readonly User $user) {}

	public function toInertiaProperty(PropertyContext $context): mixed
	{
		return $this->user->avatarUrl();
	}
}

Inertia::render('Profile', [
	'user' => $user,
	new UserPermissions($user), // canEdit, canDelete...
]);

Inertia::share('locale', 'fr');
Inertia::share(['team' => fn() => currentTeam()]);
Inertia::shareOnce('countries', fn() => CountriesDao::all());

Inertia::render('Users/Index', [
	'users' => fn() => UsersDao::all(),
	'permissions' => Inertia::defer(fn() => PermissionsDao::all()),
	'teams' => Inertia::defer(fn() => TeamsDao::all(), 'attributes'),
	'projects' => Inertia::defer(fn() => ProjectsDao::all(), 'attributes'),
	'stats' => Inertia::defer(fn() => StatsDao::compute(), rescue: true),
]);

Inertia::merge($items);                                // append at the root
Inertia::merge($items)->prepend();                     // prepend at the root
Inertia::merge($page)->append('data', matchOn: 'id');  // append to a nested array, update the items with the same id
Inertia::merge($forum)->append('posts')->prepend('announcements');
Inertia::merge($data)->append(['users.data' => 'id', 'messages']);
Inertia::deepMerge($chat)->matchOn('messages.id');
Inertia::defer(fn() => $results)->deepMerge();

$page = max(1, (int) ($_GET['page'] ?? 1));

Inertia::render('Posts/Index', [
	'posts' => Inertia::scroll(
		fn() => ['data' => PostsDao::page($page, 20)],
		ScrollMetadata::forPage($page, hasMore: $page < $lastPage),
	),
]);

'plans' => Inertia::once(fn() => PlansDao::all()),
'rates' => Inertia::once(fn() => RatesDao::all())->until(3600),        // seconds, DateInterval or DateTimeInterface
'roles' => Inertia::once(fn() => RolesDao::all())->as('roles'),         // shared by the pages using the same key
'prices' => Inertia::once(fn() => PricesDao::all())->fresh($changed),  // force a new value
'stats' => Inertia::defer(fn() => StatsDao::compute())->once(),         // also on optional and merge props

Inertia::redirect('/users');                     // 302, or 303 after PUT, PATCH and DELETE
Inertia::back();                                 // the Referer of this host, or "/"
Inertia::back('/users');                         // with a fallback
Inertia::location('https://example.com/logout'); // full page visit, 409 + X-Inertia-Location for Inertia visits
Inertia::preserveFragment();                     // keep the fragment of the visited URL across the redirect

Inertia::flash('success', 'User created.');
Inertia::flash(['success' => 'User created.', 'highlight' => $id]);
Inertia::redirect('/users');

#[Post('/users')]
public function store(): void
{
	$input = Inertia::input();
	Inertia::validate(UsersValidator::errors($input)); // ['email' => 'The email address is invalid.']

	UsersDao::add($input);
	Inertia::flash('success', 'User created.');
	Inertia::redirect('/users');
}

$router->setDefaultErrorHandler(new ErrorHandler(
	component: 'Error',                         // null to never render an error page
	pageStatuses: [403, 404, 500, 503],         // null for every status
	props: fn(HttpError $error): array => ['status' => $error->code],
	fallback: fn(HttpError $error) => HttpUtils::outputError($error->code, $error->title, $error->detail),
));

version: static fn(): string => hash_file('xxh128', __DIR__ . '/public/build/.vite/manifest.json'),

Inertia::encryptHistory();        // this page
Inertia::encryptHistory(false);   // not this page, whatever the configuration
Inertia::clearHistory();          // rotate the key, e.g. on logout: the encrypted history becomes unreadable

use Karewan\KnRouteInertia\Ssr\HttpSsrGateway;

Inertia::configure(
	rootView: __DIR__ . '/App/Views/app.php',
	ssr: new HttpSsrGateway('http://127.0.0.1:13714/render', timeout: 2.0),
);

Inertia::configure(
	rootView: $rootView,
	session: new NativeSessionStore(static fn() => AppSession::start()),
);

public function before(): void
{
	$token = $_SESSION['csrf'] ??= bin2hex(random_bytes(32));
	setcookie('XSRF-TOKEN', $token, ['path' => '/', 'samesite' => 'Lax', 'secure' => true]);

	if (!in_array(HttpUtils::getMethod(), ['GET', 'HEAD', 'OPTIONS'], true)
		&& !hash_equals($token, HttpUtils::getHeader('X-XSRF-TOKEN'))) {
		throw new HttpException(419, 'The page expired, please try again.');
	}
}