自定义路由无法正常工作 [F3]

Custom routing doesn't work correctly [F3]

自定义路由无法正常工作,总是路由到 user.htm

index.php

$routes = [
  "/" =>  "index.htm",
  "/user/id=@id" => "user.htm","/user/@id" => "user.htm",
];

foreach ($routes as $path => $file) {
  $f3->route("GET ".$path,
    function($f3){
      global $file,$path;
      echo View::instance()->render($file);
    }
  );
}

试试这个:

$routes = [
  "/" => "index.htm",
  "/user/id=@id" => "user.htm",
  "/user/@id" => "user.htm",
];

foreach ($routes as $path => $file)
{
  $f3->route("GET " . $path,
    function ($f3) use ($file)
    {
      echo View::instance()->render($file);
    }
  );
}

Bryan Velastegui 的回答是正确的。但这就是您的代码不起作用的原因:

  1. $f3->route() 将每个路由 URI 映射到一个函数(称为 "route handler"),而不执行它
  2. foreach 循环将以下值连续存储到 $file 变量中:index.htmluser.htmuser.htm(再次)。因此,在循环结束时,$file 保持 user.htm.
  3. 一旦你调用$f3->run(),框架就会执行匹配当前路由的路由处理程序,它本身引用全局$file变量,持有user.htm.

通常,您不应使用 global 关键字。这只会造成意想不到的问题,就像您遇到的问题一样。这也无助于代码的可维护性。

我建议您阅读有关 use keyword 的文档,以了解 Bryan Velastegui 的代码是如何工作的。