【发布时间】:2018-08-05 06:24:35
【问题描述】:
class Core {
protected $currentController = '';
protected $currentMethod = '';
protected $params = [];
public function __construct() {
$url = $this->getUrl();
$pages = [
"" => ["controller" => "Pages", "method" => "index"],
"profile" => ["controller" => "Pages", "method" => "profile"],
"help" => ["controller" => "Pages", "method" => "help"],
"signin" => ["controller" => "Pages", "method" => "signin"]
];
// cant access controller
$noaccess = ["pages"];
if (in_array($url[0], $noaccess)) {
redirect("/");
}
if (isLoggedIn()) {
if (!in_array($url[0], $noaccess)) {
if (!array_key_exists($url[0], $pages)) {
if (file_exists('../app/controllers/' . ucwords($url[0]) . '.php')) {
// If exists, set as controller
$this->currentController = ucwords($url[0]);
$this->currentMethod = "index";
// Unset 0 Index
unset($url[0]);
} else {
// 404
$this->currentController = "Pages";
$this->currentMethod = "error404";
unset($url[0]);
}
} else {
foreach ($pages as $page => $options) {
if ($url[0] == $page) {
$this->currentController = $options['controller'];
$this->currentMethod = $options['method'];
//unset($url[0]);
}
}
}
}
} else {
redirect("signin");
}
// 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[1])) {
// Check to see if method exists in controller
if (method_exists($this->currentController, $url[1])) {
$this->currentMethod = $url[1];
// Unset 1 index
unset($url[1]);
}
}
// 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;
}
}
}
我正在学习如何为 PHP 创建自己的 MVC 框架。我正在尝试在基于 url 实例化控制器的核心类中重定向用户。
example.com/posts/ 将实例化 Post Controller。
如果他们未登录,我想将他们重定向到/signin/。如果用户未登录,则无法访问任何页面。
我有一个名为isLoggedIn() 的基本函数,它检查$_SESSION 变量。我可以测试它是否适用于 die() 命令。
一切正常,但我收到一条错误消息,提示重定向过多。我关于$noaccess 的重定向工作没有这个问题,但我无法让loggedIn 工作。我不确定为什么会出现这个问题。
【问题讨论】:
-
如果用户未登录,则无法访问任何页面。 请记住,除了登录用户之外,每个人都必须可以访问登录页面。所以那里的逻辑发生了变化。
-
谢谢,我会补充的。在这一点上,没有人会登录,因为我必须构建它。我正在尝试先强制 /signin/ 页面。
-
是的,这是有道理的。我要说的是,如果在每个页面上都调用这个 Core 类,那么登录页面将一直重定向到自身,从而导致多次重定向。不过,这只是我的理论。我个人使用 Session 类中的方法来执行此操作,但总是在 Session 的构造函数之外。也许这会有所帮助。 (他们显然没有在课堂上使用)
-
啊,你是对的!当 url 为 /signin/ 时,我必须设置一个条件来忽略重定向。谢谢 :)。由于我的低代表,我不能投票
-
没关系,我会添加答案,您稍后可以接受。不客气!
标签: php redirect http-headers