1. Go to this page and download the library: Download devcoder-xyz/php-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/ */
devcoder-xyz / php-router example snippets
class IndexController {
public function __invoke()
{
return 'Hello world!!';
}
}
class ArticleController {
public function getAll()
{
// db get all post
return json_encode([
['id' => 1],
['id' => 2],
['id' => 3]
]);
}
public function get(int $id)
{
// db get post by id
return json_encode(['id' => $id]);
}
public function put(int $id)
{
// db edited post by id
return json_encode(['id' => $id]);
}
public function post()
{
// db create post
return json_encode(['id' => 4]);
}
}
// Define your routes
$routes = [
new \PhpDevCommunity\Route('home_page', '/', [IndexController::class]),
new \PhpDevCommunity\Route('api_articles_collection', '/api/articles', [ArticleController::class, 'getAll']),
new \PhpDevCommunity\Route('api_articles', '/api/articles/{id}', [ArticleController::class, 'get']),
];
// Initialize the router
$router = new \PhpDevCommunity\Router($routes, 'http://localhost');
try {
// Match incoming request
$route = $router->match(ServerRequestFactory::fromGlobals());
// Handle the matched route
$handler = $route->getHandler();
$attributes = $route->getAttributes();
$controllerName = $handler[0];
$methodName = $handler[1] ?? null;
$controller = new $controllerName();
// Invoke the controller method
if (!is_callable($controller)) {
$controller = [$controller, $methodName];
}
echo $controller(...array_values($attributes));
} catch (\PhpDevCommunity\Exception\MethodNotAllowed $exception) {
header("HTTP/1.0 405 Method Not Allowed");
exit();
} catch (\PhpDevCommunity\Exception\RouteNotFound $exception) {
header("HTTP/1.0 404 Not Found");
exit();
}
$route = new \PhpDevCommunity\Route('api_articles_post', '/api/articles', [ArticleController::class, 'post'], ['POST']);
$route = new \PhpDevCommunity\Route('api_articles_put', '/api/articles/{id}', [ArticleController::class, 'put'], ['PUT']);
/**
* Creates a new GET route with the given name, path, and handler.
*
* @param string $name The name of the route.
* @param string $path The path of the route.
* @param mixed $handler The handler for the route.
* @return BaseRoute The newly created GET route.
*/
public static function get(string $name, string $path, $handler): BaseRoute
{
return new BaseRoute($name, $path, $handler);
}
/**
* Creates a new POST route with the given name, path, and handler.
*
* @param string $name The name of the route.
* @param string $path The path of the route.
* @param mixed $handler The handler for the route.
* @return BaseRoute The newly created POST route.
*/
public static function post(string $name, string $path, $handler): BaseRoute
{
return new BaseRoute($name, $path, $handler, ['POST']);
}
/**
* Creates a new PUT route with the given name, path, and handler.
*
* @param string $name The name of the route.
* @param string $path The path of the route.
* @param mixed $handler The handler for the route.
* @return BaseRoute The newly created PUT route.
*/
public static function put(string $name, string $path, $handler): BaseRoute
{
return new BaseRoute($name, $path, $handler, ['PUT']);
}
/**
* Creates a new DELETE route with the given name, path, and handler.
*
* @param string $name The name of the route.
* @param string $path The path of the route.
* @param mixed $handler The handler for the route.
* @return BaseRoute The newly created DELETE route.
*/
public static function delete(string $name, string $path, $handler): BaseRoute
{
return new BaseRoute($name, $path, $handler, ['DELETE']);
}
/**
* Sets a number constraint on the specified route parameters.
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereNumber(...$parameters): self
{
$this->assignExprToParameters($parameters, '[0-9]+');
return $this;
}
$route = (new Route('example', '/example/{id}'))->whereNumber('id');
/**
* Sets a slug constraint on the specified route parameters.
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereSlug(...$parameters): self
{
$this->assignExprToParameters($parameters, '[a-z0-9-]+');
return $this;
}
$route = (new Route('article', '/article/{slug}'))->whereSlug('slug');
/**
* Sets an alphanumeric constraint on the specified route parameters.
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereAlphaNumeric(...$parameters): self
{
$this->assignExprToParameters($parameters, '[a-zA-Z0-9]+');
return $this;
}
$route = (new Route('user', '/user/{username}'))->whereAlphaNumeric('username');
/**
* Sets an alphabetic constraint on the specified route parameters.
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereAlpha(...$parameters): self
{
$this->assignExprToParameters($parameters, '[a-zA-Z]+');
return $this;
}
$route = (new Route('category', '/category/{name}'))->whereAlpha('name');
/**
* Sets a constraint for exactly two path segments separated by a slash.
*
* Example: /{segment1}/{segment2}
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereTwoSegments(...$parameters): self
{
$this->assignExprToParameters($parameters, '[a-zA-Z0-9\-_]+/[a-zA-Z0-9\-_]+');
foreach ($parameters as $parameter) {
$this->path = str_replace(sprintf('{%s}', $parameter), sprintf('{%s*}', $parameter), $this->path);
}
return $this;
}
$route = (new Route('profile', '/profile/{username}/{id}'))->whereTwoSegments('username', 'id');
/**
* Sets a constraint to match any characters.
*
* Example: /{anyPath}
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereAnything(...$parameters): self
{
$this->assignExprToParameters($parameters, '.+');
foreach ($parameters as $parameter) {
$this->path = str_replace(sprintf('{%s}', $parameter), sprintf('{%s*}', $parameter), $this->path);
}
return $this;
}
$route = (new Route('any', '/{anyPath}'))->whereAnything('anyPath');
/**
* Sets a date constraint on the specified route parameters.
*
* Example: /{date}
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereDate(...$parameters): self
{
$this->assignExprToParameters($parameters, '\d{4}-\d{2}-\d{2}');
return $this;
}
$route = (new Route('date', '/date/{date}'))->whereDate('date');
/**
* Sets a year/month constraint on the specified route parameters.
*
* Example: /{yearMonth}
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereYearMonth(...$parameters): self
{
$this->assignExprToParameters($parameters, '\d{4}-\d{2}');
return $this;
}
$route = (new Route('yearMonth', '/yearMonth/{yearMonth}'))->whereYearMonth('yearMonth');
/**
* Sets an email constraint on the specified route parameters.
*
* Example: /{email}
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereEmail(...$parameters): self
{
$this->assignExprToParameters($parameters, '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}');
return $this;
}
$route = (new Route('user', '/user/{email}'))->whereEmail('email');
/**
* Sets a UUID constraint on the specified route parameters.
*
* Example: /{uuid}
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereUuid(...$parameters): self
{
$this->assignExprToParameters($parameters, '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-5][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}');
return $this;
}
$route = (new Route('profile', '/profile/{uuid}'))->whereUuid('uuid');
/**
* Sets a boolean constraint on the specified route parameters.
*
* Example: /{isActive}
*
* @param mixed ...$parameters The route parameters to apply the constraint to.
* @return self The updated Route instance.
*/
public function whereBool(...$parameters): self
{
$this->assignExprToParameters($parameters, 'true|false|1|0');
return $this;
}
$route = (new Route('status', '/status/{isActive}'))->whereBool('isActive');
/**
* Sets a custom constraint on the specified route parameter.
*
* @param string $parameter The route parameter to apply the constraint to.
* @param string $expression The regular expression constraint.
* @return self The updated Route instance.
*/
public function where(string $parameter, string $expression): self
{
$this->wheres[$parameter] = $expression;
return $this;
}
$route = (new Route('product', '/product/{code}'))->where('code', '\d{4}');