0

想象一下,如果名称匹配,我有一个加载控制器的 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();
    }
4

2 回答 2

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);

这样,您的数组将被正确构造。无论参数是否可选,您还可以添加一些特定处理(我想您可以从我给您的代码中理解如何执行此操作;)

于 2013-10-21T15:54:12.420 回答
0

由于数据是通过 POST 发送的,因此您不需要将任何参数传递给您的方法:

class ExcelUploadController extends Controller {

    private $userName;
    private $login;

    public function ActionResult_Login() {
        $this->userName = $_POST['username'];
        $this->login = $_POST['login'];
    }
}

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

于 2013-10-21T15:48:43.173 回答