PHP code example of yiisoft / router

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

    

yiisoft / router example snippets


use Yiisoft\Router\CurrentRoute;
use Yiisoft\Router\Group;
use Yiisoft\Router\Route;
use Yiisoft\Router\RouteCollection;
use Yiisoft\Router\RouteCollectorInterface;
use Yiisoft\Router\UrlMatcherInterface;
use Yiisoft\Router\Fastroute\UrlMatcher;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;

// Define routes
$routes = [
    Route::get('/')
        ->action(static function (ServerRequestInterface $request, RequestHandlerInterface $next) use ($responseFactory) {
            $response = $responseFactory->createResponse();
            $response
                ->getBody()
                ->write('You are at homepage.');
            return $response;
        }),
    Route::get('/test/{id:\w+}')
        ->action(static function (CurrentRoute $currentRoute, RequestHandlerInterface $next) use ($responseFactory) {
            $id = $currentRoute->getArgument('id');
    
            $response = $responseFactory->createResponse();
            $response
                ->getBody()
                ->write('You are at test with argument ' . $id);
            return $response;
        })
];

// Add routes defined to route collector
$collector = $container->get(RouteCollectorInterface::class);
$collector->addGroup(Group::create(null)->routes($routes));

// Initialize URL matcher
/** @var UrlMatcherInterface $urlMatcher */
$urlMatcher = new UrlMatcher(new RouteCollection($collector));

// Do the match against $request which is PSR-7 ServerRequestInterface. 
$result = $urlMatcher->match($request);

if (!$result->isSuccess()) {
     // 404
}

// $result->arguments() contains arguments from the match.

// Run middleware assigned to a route found.
$response = $result->process($request, $notFoundHandler);

$router = $container->get(Yiisoft\Router\UrlMatcherInterface::class);
$responseFactory = $container->get(\Psr\Http\Message\ResponseFactoryInterface::class);

$routerMiddleware = new Yiisoft\Router\Middleware\Router($router, $responseFactory, $container);

// Add middleware to your middleware handler of choice.

use Yiisoft\Router\Route;

Route::delete('/post/{id}')
    ->name('post-delete')
    ->action([PostController::class, 'actionDelete']);
    
Route::methods([Method::GET, Method::POST], '/page/add')
    ->name('page-add')
    ->action([PageController::class, 'actionAdd']);

use Yiisoft\Router\Route;

Route::get('/special')
    ->name('special')
    ->action(SpecialAction::class)
    ->host('https://www.yiiframework.com');

use Yiisoft\Router\Route;

Route::get('/api[/v{version}]')
    ->name('api-index')
    ->action(ApiAction::class)
    ->defaults(['version' => 1]);

use Yiisoft\Router\Route;

Route::methods([Method::GET, Method::POST], '/page/add')
    ->middleware(Authentication::class)
    ->middleware(ExtraHeaders::class)
    ->action([PostController::class, 'add'])
    ->name('blog/add');

use Yiisoft\Router\Route;

Route::get('/special')
    ->name('special')
    ->action(SpecialAction::class)
    ->override();

use \Yiisoft\Router\Route;
use \Yiisoft\Router\Group;
use \Yiisoft\Router\RouteCollectorInterface;

// for obtaining router see adapter package of choice readme
$collector = $container->get(RouteCollectorInterface::class);
    
$collector->addGroup(
    Group::create('/api')
        ->middleware(ApiAuthentication::class)
        ->host('https://example.com')
        ->routes([
            Route::get('/comments'),
            Group::create('/posts')->routes([
                Route::get('/list'),
            ]),
        ])
);

use Yiisoft\Router\Group;
use \Tuupola\Middleware\CorsMiddleware;

return [
    Group::create('/api')
        ->withCors(CorsMiddleware::class)
        ->routes([
          // ...
        ]
    );
];

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Yiisoft\Yii\Http\Handler\NotFoundHandler;
use Yiisoft\Yii\Runner\Http\SapiEmitter;
use Yiisoft\Yii\Runner\Http\ServerRequestFactory;
use Yiisoft\Router\CurrentRoute;
use Yiisoft\Router\Route;
use Yiisoft\Router\RouteCollection;
use Yiisoft\Router\RouteCollectorInterface;
use Yiisoft\Router\Fastroute\UrlMatcher;


$request = $container
    ->get(ServerRequestFactory::class)
    ->createFromGlobals();
$responseFactory = $container->get(ResponseFactoryInterface::class);
$notFoundHandler = new NotFoundHandler($responseFactory);
$collector = $container->get(RouteCollectorInterface::class);
$collector->addRoute(
    Route::get('/test/{id:\w+}')
        ->action(static function (CurrentRoute $currentRoute, RequestHandlerInterface $next) use ($responseFactory) {
            $id = $currentRoute->getArgument('id');
            $response = $responseFactory->createResponse();
            $response
                ->getBody()
                ->write('You are at test with argument ' . $id);

           return $response;
        })
        ->name('test')
);
$router = new UrlMatcher(new RouteCollection($collector));
$route = $router->match($request);
$response = $route->process($request, $notFoundHandler);
$emitter = new SapiEmitter();
$emitter->emit($response, $request->getMethod() === Method::HEAD);

use Yiisoft\Router\UrlGeneratorInterface;

function getUrl(UrlGeneratorInterface $urlGenerator, $parameters = [])
{
    return $urlGenerator->generate('test', $parameters);
}

use Yiisoft\Router\UrlGeneratorInterface;

function getUrl(UrlGeneratorInterface $urlGenerator, $parameters = [])
{
    return $urlGenerator->generateAbsolute('test', $parameters);
}

use Yiisoft\Router\UrlGeneratorInterface;

function getUrl(UrlGeneratorInterface $urlGenerator, $id)
{
    return $urlGenerator->generateFromCurrent(['id' => 42]);
}

use \Yiisoft\Router\Route;

$routes = [
    Route::post('/post/{id:\d+}')
        ->action([PostController::class, 'actionEdit']),
];

use Psr\Http\Message\ResponseInterface
use Psr\Http\Message\UriInterface;
use Yiisoft\Router\CurrentRoute;
use Yiisoft\Router\Route;

final class PostController
{   
    public function actionEdit(CurrentRoute $currentRoute): ResponseInterface
    {
        $postId = $currentRoute->getArgument('id');
        if ($postId === null) {
            throw new \InvalidArgumentException('Post ID is not specified.');
        }
        
        // ...
    
    }
}