Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
List all available public methods for the defined class
  • Hi,
    Does anyone have any suggestions as to how I might achieve the following?

    <?php
    /**
    Cross Domain Access
    */ 
    header("Access-Control-Allow-Origin: *");

    class Controller_API_METHODS extends Controller_Rest
    {
    /*
    List all available methods for the requested class / controller
    */
    public function action_list($name)
    {
    $class_name = "\Controller_$name";
    $class_methods = get_class_methods(new $class_name());
    $this->response($class_methods);
    }
    }


    This errors with the following when I enter a valid class name:

    TypeError [ Error ]:
    Argument 1 passed to Fuel\Core\Controller::__construct() must be an instance of Fuel\Core\Request


    Thanks in advance
  • HarroHarro
    Accepted Answer
    You can't do "new $class_name" for Controllers, Controllers have required constructor arguments.

    Instead, look at reflection if you need to inspect classes: http://php.net/manual/en/reflectionclass.getmethods.php
  • Perfect, the following works:

    $class_name = "\Controller_$name";
    $class = new ReflectionClass($class_name);
    $methods = $class->getMethods();
    $this->response($methods);

    Thanks!
  • HarroHarro
    Accepted Answer
    Depending on your use-case, you might want to use

    $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC);

    to filter out protected and private methods. Also, getMethods() doesn't have the option to filter out static methods, so if you need that, you need to use

    $methods = array_diff(
        $class->getMethods(ReflectionMethod::IS_PUBLIC),
        $class->getMethods(ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_STATIC)
    );

  • Thanks for the additional info, very useful! 

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion