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:
$_GET['url'] is out of it.$_SERVER['REQUEST_URI'] $_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?
The quickest way to achieve what you want would be to just use FastRoute.
But where is fun in that :)
That said, I am a but confused about the premise of yours. Is it a REST API, which will be consumed by some other code (like in a phone or a 3rd party web app), or is it a proper website, where you just want to get pretty URLs?
Because if it's the former case, then making fancy URL parsing is completely pointless. Instead of messing round with URLs, you should be reading this article. Real REST API does not need a fancy URL parsing.
I will assume that what you are actually makingis a proper website, but with pretty URLs.
First you would have to implement a routing mechanism, which takes a list of regexp patterns, matches them agains your provided URL (which you could be extraction from $_GET['url'] or maybe $_SERVER[REQUEST_URI] (your code actually wouldn't care from where the URL was gathered ... you shouldn't be accessing superglobals inside functions/classes).
A simple version of this is explained in this answer. I am to lazy to rewrite it all =P
The second (and highly optional) part is creating code, that would take a human-readable route notation (like: /users/{id|[0-9]+}as an example) and turning it into the regular expression, which can be consumed by your routing mechanism.
If you decide to have the human-readable notations, then there are two major directions:
As for "how the end result might look like", you can probably look at the code sample here. That would illustrate one of the available option for the router's public interface.
TL;DR
Your question is vague and it is hard to understand what exactly would be helpful for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With