PHP code example of meekframework / route

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

    

meekframework / route example snippets


use Meek\Route\Collection;
use Meek\Route\Mapper;
use Meek\Route\Matcher;
use Meek\Route\Dispatcher;
use Zend\Diactoros\Response\TextResponse;
use Zend\Diactoros\ServerRequestFactory;
use Zend\Diactoros\Response\SapiEmitter;
use Meek\Route\TargetNotMatched;
use Meek\Route\MethodNotMatched;
use Psr\Http\Message\ServerRequestInterface;

// any PSR7 compliant library can be use to generate server requests
$serverRequest = ServerRequestFactory::fromGlobals();
$collection = new Collection();
$map = new Mapper($collection);
$matcher = new Matcher($collection);
$dispatcher = new Dispatcher($matcher);

$map->get('/', function (ServerRequestInterface $request) {
    // a PSR7 responses must be returned
    return new TextResponse('Hello, world!');
});

$map->get('/posts', function (ServerRequestInterface $request) {
    return new TextResponse('Viewing all posts!');
});

$map->get('/posts/:id', function (ServerRequestInterface $request) {
    return new TextResponse(sprintf('You are viewing post "%s"!', $request->getAttribute('id')));
});

// etc...
$map->head('/', function (ServerRequestInterface $request) { ... });
$map->put('/', function (ServerRequestInterface $request) { ... });
$map->post('/', function (ServerRequestInterface $request) { ... });
$map->delete('/', function (ServerRequestInterface $request) { ... });
$map->options('/', function (ServerRequestInterface $request) { ... });

try {
    $response = $dispatcher->dispatch($serverRequest);
} catch (TargetNotMatched $e) {
    $response = new TextResponse('Not Found', 404);
} catch (MethodNotMatched $e) {
    $response = new TextResponse('Method Not Allowed', 405, ['allow' => $e->getAllowedMethods()]);
}

(new SapiEmitter())->emit($response);