private function initRouter() { $this->router = new RouteCollector(); $this->router->get('/cmd{id:\\d+}', function ($id) { $controller = new Controller($this); $content = $controller->actionIncrement($id); return $content; }); $this->router->get('/cmd', function () { $controller = new Controller($this); $this->responseContentType = 'application/json'; $content = $controller->actionSummary(); return $content; }); $this->router->post('/cmd{id:\\d+}', function ($id) { $this->request->on('data', function ($data) use($id) { parse_str($data, $data); $controller = new Controller($this); $content = $controller->actionUpdate($id, $data); return $content; }); }); }
<?php include __DIR__ . '/../vendor/autoload.php'; use Phroute\Phroute\RouteCollector; use Phroute\Phroute\Dispatcher; $collector = new RouteCollector(); $collector->get('/', function () { return 'Home Page'; }); $collector->post('products', function () { return 'Create Product'; }); $collector->put('items/{id}', function ($id) { return 'Amend Item ' . $id; }); $dispatcher = new Dispatcher($collector->getData()); echo $dispatcher->dispatch('GET', '/'), "\n"; // Home Page echo $dispatcher->dispatch('POST', '/products'), "\n"; // Create Product echo $dispatcher->dispatch('PUT', '/items/123'), "\n"; // Amend Item 123
public function getDispatcher() { static $dispatcher; if ($dispatcher) { return $dispatcher; } $routes = (include $this->config['config'] . '/routes.php'); //TODO: Check if routes have been cached if (true) { $collector = new RouteCollector(); foreach ($routes as $left => $right) { // $left is something like 'GET /' // $right is a callable $left = explode(" ", $left); if (sizeof($left) === 2) { switch ($left[0]) { case 'GET': $collector->get($left[1], $right); break; case 'POST': $collector->post($left[1], $right); break; case 'ANY': $collector->any($left[1], $right); break; case 'HEAD': $collector->head($left[1], $right); break; case 'OPTIONS': $collector->options($left[1], $right); break; case 'DELETE': $collector->delete($left[1], $right); break; default: throw new ConfigException("Don't understand the HTTP method '" . $left[0] . "' in routes.php."); } } } $routeData = $collector->getData(); } return $dispatcher = new Dispatcher($routeData, $this->getHandlerResolver()); }