简体   繁体   中英

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.

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.

Now, how I can automatically grab all public function methods in that controller instead of manually put on $array variable?

You need to test if method exists and is public. 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

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 ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM