【发布时间】:2015-08-06 04:05:28
【问题描述】:
我正在构建一个基于 PHP MVC 的应用程序。我过去曾使用过 MVC 并且了解这些概念,尽管 PHP 对我来说是新事物。
我正在关注this tutorial here 来构建我的项目,并进行一些更改以反映我的需要...
我面临一个问题,即我从 form 提交回原始控制器的方式,保留上下文。 (我的低 PHP 技能可能解释了这种误解......)
让我们去代码:
这是我的 index.php(客户端每次调用的入口点):
if (isset($_GET['controller']) && isset($_GET['action']))
{
$controller = $_GET['controller'];
$action = $_GET['action'];
}
else
{
$controller = 'Root';
$action = 'home';
}
require_once('/view/layout.php');
layout.php:
<!DOCTYPE html>
<html lang="en-us">
<?php require_once("library/view/header.php"); ?> // Load header
<body>
<?php
require_once("library/controller/routes.php"); // Route controller/action
require_once("library/view/footer.php"); // Load footer
?>
</body>
routes.php:(将路径路由到正确的控制器和动作)
function call($controller, $action)
{
$filename = 'controller/class.' . $controller . 'Controller.php';
if (!file_exists($filename))
{
$errorMsg = "ERROR: File not found: " . $filename . " for Controller:" . $controller . " and Action:" . $action;
throw new Exception($errorMsg);
}
require_once ($filename);
switch ($controller)
{
case 'Root':
$controllerObj = new RootController();
break;
}
$controllerObj->{ $action }();
}
call ($controller, $action);
class.RootController.php: - Root 的控制器。
public function home ()
{
if (session_status() == PHP_SESSION_NONE)
require_once('library/view/root/login.php');
else
require_once('library/view/root/home.php');
}
public function authenticate ($username, $password)
{
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
// Authenticate logic
if ($auth == true)
{
==> Go to a different controller/view.
}
else
{
$errorMsg = "Problems authenticating.";
return $errorMsg;
}
}
public function error($controller, $action, $errorMessage)
{
echo "Error in " . $controller . ' Action" . $action;
echo $errorMessge;
}
最后是登录视图(login.php):
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>Username:</label>
<br>
<input type="text" name="username" value="<?php echo $username;?>"> <br> <br> <label>Password:</label>
<br>
<input type="password" name="password">
<br> <br>
<input type="submit" name="submit" value="Submit">
<br> <br>
<span style="color: red"><?php echo $errorMsg;?> </span>
</form>
我的问题是:
这样,当我单击提交按钮时,它会重定向到索引页面,但没有 $controller 和 $action 上下文。所以没有办法路由到RootController()上的authenticate函数;
所以,这是我的问题:
如何检查输入的数据,出错时返回错误信息或成功时更改Controller和Action?
每次数据验证都需要通过
index.php吗?是否可以直接从已经加载的
RootController()中的form到authenticate函数,失败时返回错误信息?有没有更好的方法来做这个表单验证?
我很确定我在这里遗漏了一些非常基本的东西,但我不知道什么是......
非常感谢您的帮助和帮助。
【问题讨论】:
-
header('Location: ... );或许。
标签: php forms model-view-controller