PHP code example of sethrensei / ren-router

1. Go to this page and download the library: Download sethrensei/ren-router 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/ */

    

sethrensei / ren-router example snippets


use RenRouter\RouterFactory;

$router = RouterFactory::create(__DIR__ . '/../views')
    ->withLogger($logger)               // PSR-3, optional
    ->withUrlExtension('.html')         // /contact becomes /contact.html publicly
    ->withSecurityRoute('auth.login')   // redirect target when not authenticated
    ->build();

$router
    ->get('/',        'home/index',  'home.app')
    ->get('/login',   'auth/login',  'auth.login')
    ->post('/login',  [$security, 'login'],  'auth.login.post')
    ->get('/logout',  [$security, 'logout'], 'auth.logout')
    ->get('/dashboard', 'app/dashboard', 'app.dashboard', ['auth' => true])
    ->get('/admin',     'admin/index',   'admin.index',   ['auth' => true, 'roles' => ['ROLE_ADMIN']])
    ->run();

$router = RouterFactory::create(__DIR__ . '/../templates')
    ->withTwig(
        debug:     ($_ENV['APP_ENV'] === 'DEV'),
        cachePath: __DIR__ . '/../var/cache/twig',
    )
    ->withUrlExtension('.html')
    ->build();

// A view name (rendered by the template engine)
->get('/about', 'pages/about', 'page.about')

// A callable
->get('/ping', fn(Router $r, array $p) => print('pong'), 'app.ping')

// A controller method array
->get('/users', [$userController, 'index'], 'user.index')

// A "Class@method" string
->get('/users', 'App\Controller\UserController@index', 'user.index')

->get('/user/[i:id]',        ...)   // integer
->get('/post/[a:slug]',      ...)   // alphanumeric + dash
->get('/file/[*:path]',      ...)   // anything including slashes
->get('/lang/[en|fr|de:lg]', ...)   // fixed options

->get('/dashboard', 'app/dashboard', 'app.dashboard', [
    'auth'  => true,
    'roles' => ['ROLE_USER', 'ROLE_EDITOR'],
])

use RenRouter\Security\Auth;

// Write (call right after credential verification)
Auth::login(['id' => 1, 'name' => 'Alice', 'roles' => ['ROLE_USER']]);
Auth::logout();
Auth::refreshSession();   // regenerate ID, keep data

// Read
Auth::check();                          // bool
Auth::id();                             // int|string|null
Auth::user();                           // full user array
Auth::get('name');                      // single field
Auth::roles();                          // string[]
Auth::hasRole('ROLE_ADMIN');            // bool
Auth::hasAnyRole(['ROLE_A', 'ROLE_B']); // bool — at least one
Auth::hasAllRoles(['ROLE_A', 'ROLE_B']);// bool — all 

use RenRouter\Controller\AbstractController;
use RenRouter\Router;

class PostController extends AbstractController
{
    public function __construct(Router $router)
    {
        parent::__construct($router);   // inject once, use everywhere
    }

    public function index(array $params): void
    {
        $this->nction delete(array $params): void
    {
        $this->   $this->json(['success' => true], 201);
    }
}

$twig = TwigEngine::create(viewsPath: __DIR__ . '/templates', debug: true);

$twig->addGlobal('app_name', 'MyApp');
$twig->addFunction('format_date', fn(\DateTimeInterface $d) => $d->format('d/m/Y'));
$twig->getTwig()->addExtension(new \Twig\Extension\StringLoaderExtension());

$router = RouterFactory::create(__DIR__ . '/templates')
    ->withTemplateEngine($twig)
    ->build();

// Routes are always defined without extension:
->get('/contact', 'pages/contact', 'page.contact')

// Public-facing URLs get the suffix automatically:
// /contact.html  →  ".html" camouflage (Apache/Nginx static site)
// /contact.aspx  →  ".aspx" camouflage (IIS / ASP.NET)
// /contact.jsp   →  ".jsp"  camouflage (Java / Tomcat)

RouterFactory::create(__DIR__ . '/views')
    ->withUrlExtension('.aspx')
    ->build();

$router->url('page.contact');   // https://example.com/contact.aspx
$router->path('page.contact');  // /contact.aspx

$router->setErrorRoute(404, 'error.notfound');
$router->setErrorRoute(403, 'error.forbidden');

// Absolute URL
$router->url('user.show', ['id' => 42]);
// => https://example.com/user/42.html

// Relative path
$router->path('user.show', ['id' => 42]);
// => /user/42.html

// Asset (never gets the fake extension)
$router->asset('img/logo.png');
// => https://example.com/img/logo.png

// Named redirect
$router->redirect('home.app');
$router->redirectUrl('https://example.com');

RenRouter/
├── Router.php                        Core router and dispatcher
├── RouterFactory.php                 Fluent builder for Router assembly
│
├── Controller/
│   └── AbstractController.php        Base controller (render, redirect, json, flash, guards)
│
├── Template/
│   ├── TemplateEngineInterface.php   Contract for template engines
│   ├── PhpTemplateEngine.php         Native PHP file renderer (default)
│   └── TwigEngine.php                Twig adapter (mirrors Symfony conventions)
│
├── Security/
│   └── Auth.php                      Session-based auth helper (login, logout, roles)
│
├── Http/
│   ├── Request.php                   HTTP request abstraction
│   ├── UploadedFile.php              Secure file upload wrapper
│   └── Exception/
│       ├── HttpException.php
│       ├── UnauthorizedHttpException.php   (401)
│       ├── ForbiddenHttpException.php      (403)
│       └── NotFoundHttpException.php       (404)

Using/
├── views/  (or templates/ for Twig)
│   ├── base.php                      Layout wrapper ($pg_content injected)
│   └── errors/
│       ├── 401.php
│       ├── 403.php
│       ├── 404.php
│       └── 500.php
│
└── public/
    └── index.php                     Front controller

views/errors/401.php   — Unauthorized
views/errors/403.php   — Forbidden
views/errors/404.php   — Not Found
views/errors/500.php   — Internal Server Error