BadRouter Example
source link: https://badrouter.badluck.io/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
BadRouter Example
BadRouter
About BadRouter
BadRouter is a light, simple, and easy to use router for PHP.
To get started, download BadRouter from Packagist.
https://packagist.org/packages/badluck/badrouter
composer require badluck/badrouter
BadRouter was inspired by Ruby Sinatra's design.
For context visit Sinatra: https://sinatrarb.com/intro.html
Example
This main example shows:
- How to setup routes
- How to render views
- How to customize your webapp's directories
- Start the router
<?php
require_once('vendor/autoload.php');
use BadRouter\Router;
// Setup views
Router::get('/', function() {
Router::redirect('/home');
});
Router::get('/home', function() {
$locals = [
'message' => 'Hello world!'
];
Router::render('/home', $locals);
});
Router::get('/login', function() {
Router::render('/login', [], null);
});
// Set error views
Router::set_error(404, function() {
$locals = [
'route' => parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH),
];
Router::render('/404', $locals);
});
// Configure directories
Router::set_base_path('/example');
Router::set_public('/public');
Router::set_views(__DIR__ . '/views');
// Run
session_start();
Router::run();
Static Files
Static files in .../public/...
can be accessed.
The "PUBLIC_PATH" is a global variable defined when Router::run() is called.
<img src="<?= PUBLIC_PATH ?>/images/dog.jpg" alt="dog"/>
Middleware
Middleware functions can be chained
together to handle logic before a route is rendered.
<?php
use BadRouter\Router;
// Require admin for specific routes
Router::use(function($request) {
$restricted_routes = [
'/admin',
'/admin/configuration',
];
// Check if route is restricted
if(in_array($request['route'], $restricted_routes)) {
// Check if user is logged in
if($_SESSION['is_admin'] != true) {
Router::redirect('/login');
}
}
});
// Log routes
Router::use(function($request) {
Logger::log($request);
});
Accessing Variables from Views
You can set "local" view variables from a
route and use them inside a view.
Router::get('/home', function() {
$locals = [
'message' => 'Hello world!'
];
Router::render('/home', $locals);
});
So that you can...
<p>$message = "<?= $message ?>"</p>
$message = "Hello world!"
Create APIs that return JSON.
<?php
use BadRouter\Router;
// Login using a password
Router::post('/api/login', function() {
$result = false;
if($_POST['password'] == 'rosebud') {
$result = true;
$_SESSION['is_admin'] = true;
}
Router::json([
'success' => $result,
]);
});
// Logout
Router::post('/api/logout', function() {
session_destroy();
Router::json([
'success' => true
]);
});
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK