I’ve looked for a while on this subject and there doesn’t seem to be much in the way of this specific question. I did find one answer out of hundreds that I think answers my question, but I’d like to make sure of the point. My question is, what is the best and most common way to handle a REST URI server side?
To elaborate, if I have have a URI, http://www.example.com/resources/resourceID, I know that I need to set up a .htaccess file to handle that and direct it to the right place. I am simply unsure whether it is cleaner to have a PHP dispatcher which simply parses the URI and sends off the request to specific classes (i.e. some giant switch statement that handles all HTTP methods and all possible combinations of requests that a consumer can use) or to have the .htaccess parse them. That is, do I use the .htaccess file to route the example URI to say restHandler.php or just parse it with a regex to go to a class called ‘Resources’.
This may answer my own question, but my problem with the .htaccess method is that something like http://www.example.com/resources1/resource1ID/resources2/resource2ID would be hard to capture in a regex which sends it to an appropriate file, so I lean toward a handler in PHP. But it still doesn’t seem clean to me to have a big ‘ol switch/ifelse statement to handle each possible combination that I allow. Is this really the cleanest way to go?
The best solution is a mixture of the two: use
.htaccessto capture the whole/resources1/resource1ID/resources2/resource2IDpart and redirect to a fixed entry point where this will be passed as a parameter — for example, toYour PHP code can then decide what to do with this information utilizing information that can be as rich as you want it to, including information it can gather itself at runtime (e.g. through reflection). Typically this dispatcher would utilize some kind of routing¹ to determine which controller and action should be invoked and then some type of parameter binding² to call that action with the appropriate parameters.
It could also be done through a giant
switchstatement, but that’s probably not the best idea. 😉¹ routing: mapping URL patterns to controller actions; here’s relevant reading applicable to ASP.NET, but the concept is common to all MVC frameworks
² binding: figuring out how parameters present in the URL map to formal parameters of the method that implements a controller action