我正在尝试使用 FastRoute 实现简单的 POST 请求。我按照给定的示例成功实现了 GET 类型请求。在实现 POST 请求时,我无法访问随请求发送的参数。
$dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) {
$r->addRoute('POST', '/login', 'Test/put');
$r->addRoute('GET', '/users/{id:\d+}', 'Test/put');
});
$httpMethod = $_SERVER['REQUEST_METHOD'];
$uri = $_SERVER['REQUEST_URI'];
if (false !== $pos = strpos($uri, '?')) {
$uri = substr($uri, 0, $pos);
}
$uri = rawurldecode($uri);
$routeInfo = $dispatcher->dispatch($httpMethod, $uri);
switch ($routeInfo[0]) {
case FastRoute\Dispatcher::FOUND:
$handler = $routeInfo[1];
$vars = $routeInfo[2];
list($class, $method) = explode("/", $handler, 2);
call_user_func_array(array(new $class, $method), $vars);
break;
}
class Test {
public function put() {
return "Check"; …Run Code Online (Sandbox Code Playgroud) 我知道我可以生成传递路由名称的 URL
<?php echo $this->url('route-name') #in view file ?>
Run Code Online (Sandbox Code Playgroud)
但我可以获得相反方向的信息吗?我需要从当前的 URL/URI 获取路由名称。
真实情况是:我有layout.phtml,其中顶部菜单(html)。菜单中的当前链接需要用 css 类标记。所以,我需要的例子是:
<?php // in layout.phtml file
$index_css = $this->getRouteName() == 'home-page' ? 'active' : 'none';
$about_css = $this->getRouteName() == 'about' ? 'active' : 'none';
$contact_css = $this->getRouteName() == 'contact' ? 'active' : 'none';
?>
Run Code Online (Sandbox Code Playgroud)
我正在使用快速路线,但我对任何解决方案都很感兴趣。解决方案不必位于视图文件中。