获取所有方法

I'm attempting to build a role based access control in our PHP framework. The framework is on MVC architecture so every path works on /controller/action/param. We can get the controller and action on initialization and store them in variables, $controller, $action. Now my idea is to use a class to check the permissions of this action like:

Auth::permissions($controller, $action);

Now I'm hoping I could somehow create a script which would find all public methods of controllers inside a /modules/ folder. This way I could just run a script and it would update all controller actions as a list to the database, where we would get the role permissions from. This way I could avoid inserting all controller actions manually. Getting all the controllers is very easy as the folder structure is as:

/modules
    /controller
        controller.php

So I can just find all subdirectories on modules and add .php in the end. My question is that can I get the file's public methods somehow?

class Example extends Controller {
    public function main() {
        return 'foo';
    }
}

This way I could store this in the database as

example | main | role_id

Here is a little code that can help you:

<?php
class Example {
    public function main() {
        return 'foo';
    }
    private function privatefunc(){
    }
    public function anotherpublicfunc(){
    }
}


$reflector = new ReflectionClass("Example");

foreach($reflector->getMethods() as $method){
    if($method->isPublic()) {
        echo "Method ".$method->name." is public".PHP_EOL;
    }else{
        echo "Method ".$method->name." is not public".PHP_EOL;
    }
}
?>

output:

Method main is public
Method privatefunc is not public
Method anotherpublicfunc is public

If you want to get public methods of a class then you can use get_class_methods read the doc here

class Car {

    public function permission_method_two() {

    }

    public function permission_method_three() {

    }

    private function private_function() {

    }

}

echo '<pre>'.print_r(get_class_methods('Car'),1).'</pre>';
// prints only public methods:

Array
(
    [0] => permission_method_two
    [1] => permission_method_three
)

You can follow convention: - each public methods start without lowdash - each private and protected method start with lowdash

Example

class Example
{
   public function publicMethod()
   {
   }

   private function _privateMethod()
   {
   }

   protected function _protectedMethod()
   {
   }

}

and then use http://php.net/manual/ru/function.get-class-methods.php

foreach(get_class_methods('Example') as $methodName){
   if(strpos($methodName, '_') !== 0) $publicMethod[] = $methodName; 
}