PHP code example of york8 / router

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

    

york8 / router example snippets


$router = new Router(function notFound() { ... });

$router->get(...);
$router->post(...);
$router->put(...);
$router->head(...);
$router->option(...);
$router->delete(...);
$router->addRuler(...);

class PathMatcher implements MatcherInterface
    /**
     * @param \string[] $paths 需要匹配的路径列表,路径规则如下:
     * <p> /path/to/target
     * <p> /path/to/(pattern)/target 括号内为正则表达式
     * <p> /path/:attr1(pattern)/to/:attr2(pattern) 命名的正则表达式,匹配到值将设置到请求对象的 attributes 中
     * @param string $prefix
     * @param bool $isCaseSensitive 是否匹配大小写,默认忽略大小写
     */
    public function __construct(array $paths, $prefix = null, bool $isCaseSensitive = false)
    {
        // ...
    }

    /**
     * @param string $path
     * @param string[]|null $attrs
     * @return bool
     * @throws \RuntimeException
     */
    public function match($path, array &$attrs = null): bool
    {
        // ...
    }

    // ...
}

$attrs = [];
$handler = $router->route($request, $attrs);

$response = $handler->handle($request, $response);


// 1. create Router with default not found handler
$router = new Router(function (ServerRequestInterface $request, ResponseInterface $response) {
    $response = $response->withStatus(404);
    $body = $response->getBody();
    $body->write('Not Found: ' . $request->getUri()->getPath());
    return $response;
});
// 2. build the router rules
$router->get(
    '/account/:username',
    function (ServerRequestInterface $request, ResponseInterface $response) {
        $username = $request->getAttribute('username');
        $body = $response->getBody();
        $body->write("Hello, $username!");
        return $response;
    }
);

// 3. initialize the request
$request = ServerRequest::fromGlobals();

// use the 'php://output' stream for the response body directly
$body = fopen('php://output', 'w+');
// 3. initialize the response
$response = new Response(200, [], $body);

// 4. route the request and get the handler
$attrs = [];
$handler = $router->route($request, $attrs);

// set the request attributes with the 'attrs' of route result
foreach ($attrs as $attrName => $attrValue) {
    $request = $request->withAttribute($attrName, $attrValue);
}

// 5. handle the request
$response = $handler->handle($request, $response);