teslex/solovey-router

Simple PHP Router

1.1.0 2018-09-27 16:54 UTC

This package is not auto-updated.

Last update: 2021-02-26 05:21:55 UTC


README

Simple PHP Router

- Usage

composer require teslex/solovey-router

Simple example:

<?php

require_once __DIR__ . "vendor/autoload.php";

use SoloveyRouter\Exception\RouterException;
use SoloveyRouter\Router;

$router = new Router();

$router->get('/', function () {
	print "root";
});

$router->post('/api/user/{n}', function ($userId) {
	print $userId;
});

try {
	$router->go($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']);
} catch (RouterException $e) {
	throw $e;
}

Custom regex patterns:

$router->pattern('email', '([-0-9a-zA-Z.+_]+@[-0-9a-zA-Z.+_]+.[a-zA-Z]{2,4})');

$router->get('/{email}/send/', function ($email) {
	print $email;
});

Custom methods:

$router->route(new Route($router, 'PUT|DELETE|POST', '/someurl', function () {
	print "some response";
}));

Groups:

$router->group('/api/user', [
	'/getById/{n+}' => function (int $userId) {
		print "user $userId";
		// as GET
	},
	'POST' => [
		'/updateEmail/{n+}/{email}' => function (int $userId, $email) {
			print "$userId $email";
		}, 
		// ...
	]
	// any another method or methods
]);

$router->group('/api', function (Router $router) {
	$router->get('/all', ..)->name('get all');
	$router->post('/save', ..);
});

Middleware:

$router->get('/mid', function () {
	print "after middleware";
})
->middleware(Middleware::class);
// ->middleware(Middleware::class, 'method');
// ->middleware(function () {});

// to routes group
$router->group('/api/mid', [
	'/something' => function () {
		print "after middleware";
	}
])->middleware(Middleware::class); // allow to all routes

class Middleware {
	function index() {
		// do something
	}
}

Listen all requests (use it after all routes):

$router->any('/*', function () {
	print "all of all";
});