Feralheart
Feralheart

Reputation: 1928

Laravel: How to get the action names from a controller and their params as a string?

I looking for a function where I give a ControllerName as a param and it returns the functions in that controller. For example:

.
.
.
class ExampleController extends Controller {

  public static function firstExample($param1 = ' ', $param2 = 0){
   .
   .
   .
  }

  public static function secondExample($param3){
   .
   .
   .
  }
}

And if I call: $actions = MyController::getActions('ExampleController');

It outputs this structure:

array(
  0 => array(
   'name' => 'firstExample'
   'params' => array(
     0 => '$param1',
     1 => '$param2',
   )
 ),
 1 => array(
   'name' => 'secondExample'
   'params' => array(
     0 => '$param3',
   )
  )
);

I know how to write functions and controllers. My question is: how to get the function names and their params (and maybe their types if it's possible, too) from a different controller?

Upvotes: 0

Views: 556

Answers (1)

PedroFaria99
PedroFaria99

Reputation: 484

So if I understood correctly you want to get the methods of any controller, and their respective parameters.

Step 1 : Getting the methods name

Using the PHP's get_class_methods you can retrieve all the methods of a specific class.

function getActions($controllerName){
   $class_methods = get_class_methods(controllerName); //getting them
   foreach ($class_methods as $method_name) {          //looping them
      getParams($controllerName,$method_name);
   }
}

Step 2 : Getting the methods parameters

Using PHP's ReflectionMethod class:

function getParams($controllerName,$method_name){
   $method = new ReflectionMethod($className, $methodName);
   $params = $method->getParameters();
   foreach ($params as $param) {
     echo $param->getName(); //add to array here
   }
}

Now for getting the type, not sure if $param->getType() works, but it's just a matter of trying, anyway this is just the basic stuff, now you can manipulate the function to fit your needs.

Note: Not sure if there's a better way that comes with Laravel, this is a vanilla PHP way of doing it.

Best Regards.

Upvotes: 1

Related Questions