我的 composer.json
{
"require": {
"symfony/routing": "^3.2"
}
}
我的 index.php
<?php
include './vendor/autoload.php';
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\HttpFoundation\Request;
class Christopher {
public $context;
public $routes;
public function __construct() {
$context = new RequestContext();
$this->context = $context->fromRequest(Request::createFromGlobals());
$this->routes = new RouteCollection();
}
public function route($methods, $path, $controller) {
$this->routes->add($path, new Route(
$path,
[
'_controller' => $controller
],
[
'id' => '[0-9]'
],
[],
'',
[],
$methods
));
}
public function dispatch() {
$matcher = new UrlMatcher($this->routes, $this->context);
try {
$matcher = $matcher->match($_SERVER['REQUEST_URI']);
call_user_func_array($matcher['_controller'], array_slice($matcher, 1, -1));
} catch (MethodNotAllowedException $e) {
echo 'Route method is not allowed.';
} catch (ResourceNotFoundException $e) {
echo 'Route does not exist.';
}
}
}
$christopher = new Christopher();
$christopher->route('GET', '/posters', function () {
echo '<a href="/posters/1">1. Poster</a>';
});
$christopher->route('GET', '/posters/{id}', function ($id) {
echo 'ID - ' . $id;
});
$christopher->dispatch();