如何从url参数获取函数参数-nginx重写?

时间:2018-10-24 07:03:59

标签: php nginx url-routing

我想将基于对象的PHP脚本重建为一个简单的框架,并阅读了一些教程来学习。目前,我停留在该部分如何将参数从url传递到函数参数(similar to here

通过控制器和方法可以正常工作,但是第一个参数(在我的情况下为id)不会通过正确的索引传递给我,而我的代码来自以下网址:

url: https: // Domain/controller/method/params

这就是我要从url获取信息的地方:

 public function __construct(){
  //print_r($this->getUrl());

  $url = $this->getUrl();

  // Look in controllers for first value
  if(file_exists('../app/controllers/' . ucwords($url[1]). '.php')){

  // If exists, set as controller
  $this->currentController = ucwords($url[1]);

  // Unset 0 Index
  unset($url[1]);
  }

  // Require the controller
  require_once '../app/controllers/'. $this->currentController . '.php';

  // Instantiate controller class
  $this->currentController = new $this->currentController;

  // Check for second part of url
  if(isset($url[2])){
    // Check to see if method exists in controller
    if(method_exists($this->currentController, $url[2])){
      $this->currentMethod = $url[2];
      // Unset 2 index
      unset($url[2]);
    }
  }

  // Get params
  $this->params = $url ? array_values($url) : [];

  // Call a callback with array of params
 call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
}

public function getUrl(){
  if(isset($_GET['url'])){
    $url = rtrim($_GET['url'], '/');
    $url = filter_var($url, FILTER_SANITIZE_URL);
    $url = explode('/', $url);
    return $url;
  }
}

据我了解,所有魔术都发生在这里:

call_user_func_array([$this->currentController, $this->currentMethod], $this->params);

但是,如果我尝试在控制器函数中回显该参数,则该参数为空:

public function test($id){
  echo $id;
}

这是可行的,但是来自url的第一个参数作为$ id2传递:

public function test($id, $id2){
  echo "First:";
  echo $id; //empty
  echo "Second:";
  echo $id2; //(ID) 1
}
Url: https:// Domain/controller/test/1

所以我想这可能与Nginx重写规则和get_url的结果有关。有关文件夹结构,我测试了一些nginx规则,以得到与htaccess apache版本相同的结果,但是仍然有所不同。因此,为了传递控制器和方法,我已经不得不将数组索引设置为+1(请参见上面的代码)。

print_r($this->getUrl()); 
Result: Array ( [0] => [1] => controller [2] => test [3] => 1 )

索引[0]来自目录结构,并捕获公用文件夹。在htaccess的apache版本中,此文件夹未在url数组中捕获。那么这也许是导致我出现问题的原因吗?

目录结构:

web (server doc root)
- public (public folder after using rewrites)
- app

htaccess与here相同。除了相似的规则外,nginx上的结果每次都相同。这是我目前使用的规则:

location /{FOLDER} {
client_max_body_size 100M;
root {DOCROOT}/{FOLDER}public;
index  index.php;

try_files $uri $uri/ /{FOLDER}index.php?url=$uri&$args;

location ~ \.php$ {
try_files $uri =404;
include /etc/nginx/fastcgi_params;
{FASTCGIPASS}
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
#fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_intercept_errors on;

fastcgi_param HTTP_AUTHORIZATION $http_authorization;

}
}

但是,也许这个问题与nginx规则无关。 正如我已经说过的,我被困在这里...

谢谢!

1 个答案:

答案 0 :(得分:0)

看起来像这样解决了它:

// Unset 0 Index
  unset($url[0]);
  unset($url[1]);