I’m writing an API class, and my general goal is for it to be easy to make any class’s methods accessible via the API, without having to make any serious changes to the class itself. Essentially, I should be able to instantiate an API class instance on any class that I want to use (within my little framework), and have it just work.
For example, In my API class, I have a method call, that I want to use $_GET to call the correct function from the class that I want to make accessible (let’s call it Beep). So I specify an action parameter in my API, so that the action is the method of Beep to call, with the remaining arguments in $_GET being, presumably, the arguments for the method. In API->call, I can do $BeepInstance->$_GET['action'](), but I have no way of determining which arguments from $_GET to send, and in what order to send them.
func_get_args will only return the list of given arguments for the function in which it is called, and I don’t necessarily know the correct order in which to pass them with call_user_func_array.
Has anyone tried to do something similar to this?
Here’s a solution + example that uses reflection to map your input arguments to method parameters. I also added a way to control which methods are exposed to make it more secure.
Example: