PHP code example of karewan / knroute

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


declare(strict_types=1);

use Karewan\KnRoute\Router;

// Init the router
$router = new Router();

// Scan controllers, register routes and optionnaly cache them
$router->registerRoutesFromControllers(
	// Folder to be scanned
	controllersPath: __DIR__ . '/App/Controllers',
	// Use cache only for prod (do not forget to clear cache after deploy)
	cacheFile: DEBUG ? null : __DIR__ . '/tmp/cache.php'
);

// Run the router (nothing will be executed below this line)
$router->run();

// All HTTP methods
#[Any('/test')]

// HTTP DELETE method
#[Delete('/test')]

// HTTP GET method
#[Get('/test')]

// HTTP PATCH method
#[Patch('/test')]

// HTTP POST method
#[Post('/test')]

// HTTP PUT method
#[Put('/test')]

// Use an array of HTTP methods
#[Route(['GET', 'POST'], '/test')]

declare(strict_types=1);

namespace App\Controllers;

use Karewan\KnRoute\Attributes\Get;
use Karewan\KnRoute\Attributes\Post;
use Karewan\KnRoute\HttpUtils;

class IndexController
{
	#[Get('/')]
	public function index(): never
	{
		HttpUtils::outputText("IndexController@index\n");
	}

	#[Post('/login')]
	public function login(): never
	{
		HttpUtils::outputJson(['error' => 'Bad credentials']);
	}
}

#[Post('/amd/{id:num}/ryzen/{model:alpha}')]
public function topSecret(int $id, string $model):void {
	echo "AmdController@topSecret(id={$id},model={$model})";
}

declare(strict_types=1);

namespace App\Middlewares;

use Attribute;
use Karewan\KnRoute\HttpUtils;
use Karewan\KnRoute\IMiddleware;

#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class AuthMiddleware implements IMiddleware
{
	/**
	 * Do your logic here
	 * @return void
	 */
	public function handle(): void
	{
		if(!isLogged()) {
			HttpUtils::dieStatus(401);
		}
	}
}

declare(strict_types=1);

namespace App\Controllers;

use App\Middlewares\AuthMiddleware;
use Karewan\KnRoute\Attributes\Get;
use Karewan\KnRoute\HttpUtils;

#[AuthMiddleware()]
class TestController
{
	#[Get('/')]
	public function index(): void
	{
		HttpUtils::outputText("TestController@index\n");
	}
}

declare(strict_types=1);

namespace App\Controllers;

use App\Middlewares\AuthMiddleware;
use Karewan\KnRoute\Attributes\Get;
use Karewan\KnRoute\HttpUtils;

class TestController
{
	#[Get('/'), AuthMiddleware()]
	public function index(): void
	{
		HttpUtils::outputText("TestController@index\n");
	}
}

declare(strict_types=1);

namespace App\Middlewares;

use Attribute;
use Karewan\KnRoute\HttpUtils;
use Karewan\KnRoute\IMiddleware;

#[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class SecretMiddleware implements IMiddleware
{
	/**
	 * Class constructor
	 * @param null|int $ype})\n");
		}
	}
}

declare(strict_types=1);

namespace App\Controllers;

use App\Middlewares\SecretMiddleware;
use Karewan\KnRoute\Attributes\Get;
use Karewan\KnRoute\HttpUtils;

#[SecretMiddleware(

function getHost(): string;
function getPath(): string;
function getMethod(): string;
function getProtocol():string;
function hasHeader(string $name): bool;
function getHeader(string $name): string;
function getHeaders(): array;
function setHeader(string $key, string $value, int $httpCode = 0, bool $replace = true): void;
function getQueryString(): string;
function getContentType(): string;
function getContentLength(): string;
function getUserAgent(): string;
function getLanguages(): string;
function getAcceptEncoding(): string;
function getReferer(): string;
function getIp(): string;
function getServerPort(): int;
function getClientPort(): int;
function getBody(): string;
function getJsonBody(bool $associative = false, int $depth = 512, int $flags = JSON_BIGINT_AS_STRING): mixed;
function outputJson(mixed $data, int $httpCode = 200): never;
function outputHtml(string $html, int $httpCode = 200): never;
function outputText(string $text, int $httpCode = 200): never;
function location(string $path = '/', int $httpCode = 302): never;
function dieStatus(int $code): never;

IS_XHR

declare(strict_types=1);

use Karewan\KnRoute\Plugins\Inertia\Inertia;
use Karewan\KnRoute\Router;

// App / Assets version
const APP_VERSION = 'b3d5e9f30';

// Init Inertia
Inertia::init(
	// Use your view rendering method here with your Template file (from your framework or your custom method)
	viewFnc: fn(array $data): string => view('MyTemplate', $data),
	// Assets version (not mandatory)
	version: APP_VERSION
);

// Router...
$router = new Router();

/**
 * Return the content of a view file
 * @param string $view
 * @param array $data
 * @return string
 */
function view(string $view, array $data = []): string
{
	ob_start();
	extract($data, EXTR_OVERWRITE);
	

<!DOCTYPE html>
<html>

<head>
...
</head>

<body>
	<!-- This will append the Inertia data-page JSON -->
	<div id="app" <?= $inertiaPage 

declare(strict_types=1);

namespace App\Controllers;

use Karewan\KnRoute\Attributes\Get;
use Karewan\KnRoute\HttpUtils;
use Karewan\KnRoute\Plugins\Inertia\Inertia;

class TestController
{
	#[Get('/')]
	public function index(): void
	{
		Inertia::render('Index', [
			'data1' => 'data1',
			'data2' => fn() => 'data2',
			'data3' => Inertia::lazy(fn() => 'data3'),
			'data4' => Inertia::always('data4')
		]);
	}
}

declare(strict_types=1);

use Karewan\KnRoute\Plugins\Inertia\Inertia;

// One key
Inertia::share('user', 'John Doe');
// OR a full array
Inertia::share([
	'user', 'John Doe',
	'foo' => []
]);

declare(strict_types=1);

use Karewan\KnRoute\Plugins\Inertia\Inertia;

// One key
Inertia::viewData('foo', 'bar');
// OR a full array
Inertia::viewData([
	'foo', 'bar',
	'fooArr' => []
]);

<!DOCTYPE html>
<html>

<head>
...
</head>

<body>
	<div id="app" <?= $inertiaPage 

function init(Closure $viewFnc, string $version = ''): void;
function getVersion(): string;
function viewData(string|array $key, mixed $data): void;
function getViewData(): array;
function flushViewData(): void;
function share(string|array $key, mixed $data): void;
function getShared(): array;
function flushShared(): void;
// Inertia redirect (this initiate a full page reload on the client side)
function location(string $url = '/'): never;
function always(mixed $data): AlwaysProp;
function lazy(Closure $data): LazyProp;
function render(string $component, array $props = []): never;

IS_INERTIA