Currenntly I am working on a simple MVC framework of mine. So my Core library loads the controller and method based on the URL with the given parameters. The parameters are an array after exploding the URL. This is done by using call_user_func_array([$controller, $method], $params)
. However if the user passes only 1 parameter from the URL and the method requires 2 it will show an ArgumentCount Error
.
For example: localhost/app/controller1/method1/param1
is the URL so controller1 and method1 are loaded after checking if they exist. However if the method is such that it accepts minimum 2 parameters like: public function method1(int param1, int param2)
it will give the error. Therefore I need to check if the the number of args passed in the URL are equal.
I thought of doing this using Reflection
like checking if the Arg Counts are equal in the method called and parameters given. This is my code:
$this->params = $url ? array_values($url) : [];
// Call a callback with an array of parameters
$r = new ReflectionMethod($this->currentController, $this->currentMethod);
$argCount = $r->getNumberOfRequiredParameters();
if($argCount == count($this->params)) {
call_user_func_array([$this->currentController, $this->currentMethod], $this->params);
} else {
die("Arg count incorrect");
}
However this system won't work if I had some optional parameters in the method.
For example: public function method1($required, $optional = 'bar')
. Therefore would there be a way to call the method if atleast all required params are given and use optional params if specified. This is the code for my core library Core
Aucun commentaire:
Enregistrer un commentaire