[英]Auto mapping method parameters to $_POST data (MVC)
想象一下,如果名称匹配,我有一个加载控制器的URL(此刻忽略任何与此相关的安全问题)
public function Load( $controller, $action = "Index" )
{
require_once( "Controllers/" . $controller . "Controller.php" );
$controllerName = $controller . "Controller";
$loadedController = new $controllerName();
$actionName = "ActionResult_" . $action;
$loadedController->$actionName();
}
现在想象一下,我想要一个登录表单来发送其$ _POST详细信息作为上面启动的接收控制器的参数:
<?php
class ExcelUploadController extends Controller
{
public function ActionResult_Login( $username = NULL, $password = NULL )
{
// The parameters need to be mapped to the $_POST parameters names probably from the Load method somewhere and pumped in to the $loadedController->$actionName();
$post_username = $username;
$post_password = $password;
$this->ReturnView( "ExcelUpload/Index" );
}
}
?>
而且还可以使参数的声明顺序无关紧要,它基于$ _POST键与函数中的参数匹配。
任何想法,我将如何去做?
因此,请澄清这是否没有道理..该方法可能看起来像这样:
public function Load( $controller, $action = "Index" )
{
require_once( "Controllers/" . $controller . "Controller.php" );
$controllerName = $controller . "Controller";
$loadedController = new $controllerName();
$actionName = "ActionResult_" . $action;
$checkIfPostData = $_POST;
if( isset( $checkIfPostData ) )
{
// Do some funky wang to map the following $loadedController->$actionName();
// with the username and password or any other $_POST keys so that in the calling method, I can grab hold of the $_POST values
}
$loadedController->$actionName();
}
您正在寻找的是call_user_func_array()
编辑,以回复评论:您有两个选择:重写所有函数,以便它们仅接受一个array()作为参数,然后解析该数组以获取值。 有点讲究,但在某些情况下可能很有用。 或者,您可以请求函数的必需参数:
// This will create an object that is the definition of your object
$f = new ReflectionMethod($instance_of_object, $method_name);
$args = array();
// Loop trough params
foreach ($f->getParameters() as $param) {
// Check if parameters is sent through POST and if it is optional or not
if (!isset($_POST[$param->name]) && !$param->isOptional()) {
throw new Exception("You did not provide a value for all parameters");
}
if (isset($_POST[$param->name])) {
$args[] = $_POST[$param->name];
}
if ($param->name == 'args') {
$args[] = $_POST;
}
}
$result = call_user_func_array(array($instance_of_object, $method_name), $args);
这样,您的数组将被正确构造。 您还可以添加一些特定的处理方式,不管参数是否可选(我想您可以从我给您的代码中了解如何实现;)
由于数据是通过POST发送的,因此您无需将任何参数传递给您的方法:
class ExcelUploadController extends Controller {
private $userName;
private $login;
public function ActionResult_Login() {
$this->userName = $_POST['username'];
$this->login = $_POST['login'];
}
}
不要忘了清理和验证用户输入!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.