如何在控制器中获取所有公共函数方法


How I can grab all public function methods in a controller?

我使用__remap()函数来避免任何未定义的方法,并使其重定向到index()函数

function __remap($method)
{
   $array = {"method1","method2"};
   in_array($method,$array) ? $this->$method() : $this->index();
}

该函数将检查除method1和method2之外的其他方法。它将重定向到索引函数。

现在,我如何能自动抓取所有的公共函数方法在该控制器而不是手动放在$array变量?

您需要测试方法是否存在并且是公共的。所以你需要使用反射和方法存在。像这样:

function __remap($method)
{
    if(method_exists($this, $method)){
        $reflection = new ReflectionMethod($this, $method);
        if($reflection->isPublic()){
            return $this->{$method}();
        }
    }
    return $this->index();
}

或者您可以使用get_class_methods()来创建方法数组

好吧,我很无聊:

$r = new ReflectionClass(__CLASS__);
$methods = array_map(function($v) {
                        return $v->name;
                     },
                     $r->getMethods(ReflectionMethod::IS_PUBLIC));

我修改了代码,变成了这样。

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

任何增强而不是使用foreach?