想象一下,如果名称匹配,我有一个加载控制器的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();
}
答案 0 :(得分:1)
您正在寻找的是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);
这样你的数组就会被正确构建。 你也可以添加一些特定的处理,无论参数是否可选(我想你可以从我给你的代码中理解如何做到这一点;)
答案 1 :(得分:0)
由于数据是通过POST发送的,因此您无需将任何参数传递给您的方法:
class ExcelUploadController extends Controller {
private $userName;
private $login;
public function ActionResult_Login() {
$this->userName = $_POST['username'];
$this->login = $_POST['login'];
}
}
不要忘记清理并验证用户输入!