PHP code example of chi-teck / micro-router

1. Go to this page and download the library: Download chi-teck/micro-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/ */

    

chi-teck / micro-router example snippets


$routes = new RouteCollection();

$routes['article.view'] = new Route(
    methods: ['GET'],
    path: '/article/{id}',
    e/{id}',
    
    : ArticleCreateHandler::class,
);

$routes = new RouteCollection();
$routes['article.view'] = Route::create('GET', '/article/{id:\d+}', ArticleViewHandler::class);
$routes['article.update'] = Route::create('PUT', '/article/{id:\d+}', ArticleUpdateHandler::class);
$routes['article.delete'] = Route::create('DELETE', '/article/{id:\d+}', ArticleDeleteHandler::class);
$routes['article.create'] = Route::create('POST', '/article', ArticleCreateHandler::class);

use MicroRouter\Contract\Exception\MethodNotAllowedInterface;
use MicroRouter\Contract\Exception\ResourceNotFoundInterface;
use MicroRouter\Matcher;

/** @var \MicroRouter\Contract\RouteCollectionInterface $routes */
$routes =  globals.
$request = $request_factory->createServerRequest('GET', '/article/123');
try {
    $result = $matcher->match($request, $routes);
    $handler = $result->getRoute()->getHandler();
    // Depending on handler type (closure, service ID, etc) you may need to
    // resolve the callable before invoking.
    $response = $handler(...$result->getParameters());
}
catch (ResourceNotFoundInterface) {
    /** @var \Psr\Http\Message\ResponseFactoryInterface $response_factory */
    $response = $response_factory->createResponse(404);
}
catch (MethodNotAllowedInterface $exception) {
    /** @var \Psr\Http\Message\ResponseFactoryInterface $response_factory */
    $response = $response_factory->createResponse(405)
        ->withHeader('Allowed', $exception->getAllowedMethods());
}