自动将方法参数映射到 $_POST 数据 (MVC)


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'];
    }
}

不要忘记清理和验证用户输入!