如何编写一个将数组作为URL参数发送的控制器?
In some MVC platforms, a controller method accepts an URL's contents as forward-slash separated list of elements, received as parameters, e.g.
site.com/controller/method/var1/var2
has associated controller:
class Controller
function method(var1, var2){
}
}
But how can I achieve this coding? I wish to start with an array and send a parameterized list to a function, i.e.
$args = array("one"=>"cheese","two"=>"eggs");
php_function("myfunction",$args);
Within myfunction
, I would have
function myfunction($one, $two){
}
I know about func_get_args
for accepting an unknown number of arguments. user_call_func
is useful except
user_call_func("myfunction",$args);
...results in the first parameter containing an array of arguments, no difference to func_get_args
called from within the function.
extract
doesn't work either as I need to receive the array as a variable inside the function.
在某些MVC平台中,控制器方法接受URL的内容作为正斜杠分隔的元素列表,作为参数接收 ,例如 p>
site.com/controller/method/var1/var2
nn有关联的控制器: p>
类Controller
函数方法(var1,var2){
}
}
code> pre>
但是 我怎样才能实现这种编码? 我希望从数组开始并将参数化列表发送到函数,即 p>
$ args = array(“one”=>“cheese”,“two”= >“eggs”);
php_function(“myfunction”,$ args);
code> pre>
在 myfunction code>中,我会 p>
function myfunction($ one,$ two){
}
code> pre>
我知道 func_get_args code>用于接受未知数量的参数。 user_call_func code>非常有用,除了 p>
user_call_func(“myfunction”,$ args);
code> pre>
...导致第一个参数包含一个参数数组,与函数内部调用的 func_get_args code>没有区别。 p>
extract code>不起作用,因为我需要将数组作为函数内的变量接收。 p>
div>
I've managed to create your desired with the following.
class BootStrap {
private $controller = 'NameOfIle.php';
private $method = 'function()';
private $params = array('sdfds' => 'dsfdsf', 'sdfdsfsdfdsfsd' => 'sdfdsfds');
public function __construct() {
call_user_func_array(array($this->controller, $this->method), $this->params);
}
}
call_user_func_array
takes a method description and an array of arguments, and returns the result of calling the function. I think it will take the arguments from the array in order though, rather than by name. You should assemble an array of the arguments in the correct order, and perhaps validate for missing arguments, before using this.