【发布时间】:2018-10-24 07:03:58
【问题描述】:
我想将我的基于对象的 PHP 脚本重建为一个简单的框架,并阅读了一些教程以从中学习。目前我停留在如何将参数从 url 传递到函数参数的部分 (similar to here)
传递控制器和方法工作正常,但第一个参数(在我的情况下为 id)将不会传递 - 在正确的索引上 - 我的代码来自 url,例如:
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] 来自 dir 结构并捕获公共文件夹。在 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 规则无关。 正如我已经说过的那样,我被困在这里......
谢谢!
【问题讨论】:
标签: php nginx url-routing