I am a bit familiar with PHP MVC. Say, I have a controller like so:
class Customers{
public function method1( param1, param2, param3, ..., param_n ){
}
}
In my bootstraping page, I can grab a browser URL like so:
$url = explode('/', filter_var(rtrim( $_GET['url'], '/' ), FILTER_SANITIZE_URL));
I do $controller = $url[0]
and $method = $url[1]
. Any other elements in $url
after the second index are parameters and can be collected into an array variable, say $params
. Then I route to the relevant controller method and parameters like so:
call_user_func_array([$controller, $method], $params);
PLEASE NOTE: Above code is for illustration purposes. I always do checks in real-life situations. Those checks are not shown here, so do not use the above examples for serious projects.
Now, I want to implement a RESTful API using MVC pattern. What I already know:
- No browser is involved, so
$_GET['url']
is out of it. - The endpoint is obtained from
$_SERVER['REQUEST_URI']
- The method is obtained from
$_SERVER['REQUEST_METHOD']
How do I route to an endpoint, for example, customers/{12345}/orders
to get the orders of a particular customer with id 12345
?
How can I do this?