[英]How I can grab all public function methods in a controller?
I use __remap()
function to avoid any undefine method and make it redirect to index() function. 我使用
__remap()
函数来避免任何未定义的方法,并将其重定向到index()函数。
function __remap($method)
{
$array = {"method1","method2"};
in_array($method,$array) ? $this->$method() : $this->index();
}
That function will check if other than method1 and method2.. it will redirect to index function. 该函数将检查method1和method2以外的其他内容。它将重定向到索引函数。
Now, how I can automatically grab all public function methods in that controller instead of manually put on $array
variable? 现在,如何才能自动获取该控制器中的所有公共函数方法,而不是手动放置
$array
变量?
You need to test if method exists and is public. 您需要测试method是否存在并且是公共的。 So you need use reflection and method exists.
因此,您需要使用反射和方法存在。 Something like this:
像这样:
function __remap($method)
{
if(method_exists($this, $method)){
$reflection = new ReflectionMethod($this, $method);
if($reflection->isPublic()){
return $this->{$method}();
}
}
return $this->index();
}
Or you can use get_class_methods() for create your array of methods 或者您可以使用get_class_methods()创建方法数组
OK, I was bored: 好吧,我很无聊:
$r = new ReflectionClass(__CLASS__);
$methods = array_map(function($v) {
return $v->name;
},
$r->getMethods(ReflectionMethod::IS_PUBLIC));
I've modified the codes and become like this. 我已经修改了代码,变得像这样。
function _remap($method)
{
$controllers = new ReflectionClass(__CLASS__);
$obj_method_existed = array_map(function($method_existed)
{
return $method_existed;
},
$controllers->getMethods(ReflectionMethod::IS_PUBLIC));
$arr_method = array();
//The following FOREACH I think was not good practice.
foreach($obj_method_existed as $method_existed):
$arr_method[] = $method_existed->name;
endforeach;
in_array($method, $arr_method) ? $this->$method() : $this->index();
}
Any enhancement instead of using foreach ? 是否有任何改进而不是使用foreach ?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.