Hello my friend,
if you are here you are probably looking for a simple but powerful piece of code for your PHP project which is just about to be kicked off.
Before we start, let’s say something undeniable… we have a plethora, in the PHP ecosystem, of libraries and frameworks that let you (quite easily) implement a REST service for your solution; I’m not here to tell you which one of them is the best, if you want otherwise to understand what it might be at their deepest core, you’ll get some hints reading this story.
Let’s start from some basic concepts
What is a route and how it is handled
If you want to describe what a REST web service does, you would probably say that…
> it is capable to expose data under a given entry point
> every HTTP method describes an action:
- GET for reading
- POST for creating
- PUT for updating
- DELETE for … yeah, you got it :-)
(we might have other methods but let’s keep it stupid simple)
> each route might have attributes and an intrinsic syntactic meaning.
“GET /users/1337/comments” — read all the comments for the user with ID 1337.
Who is in charge to recognize and give directions towards one of these routes?
The router. A function that, in very few words, tries to match a pattern (our route definition) over the request URL and, if satisfied, it does apply a logic specifically for that request.
How to apply a common logic to the routes
What if I have to do something every time, for each response? Do I have to replicate my code in every router?
For the sake of Chtuluh, no!
We have a thing called “middleware”; very similar to the router but called before the completion of every response, no matter what… and we might have lots of them, all executed in waterfall.
Now that we know the theoretical domain, let’s move into coding
The router function itself is pretty straightforward… it gets 3 arguments, an HTTP method, a string representing the route to be matched and a callback function to be called afterwards.
Plus, if there are parameters defined in the regular expression, that describe the route, it applies those coming from the request.
Once defined, it is possible to register the routes with the respective callbacks.
If provided, the callback will receive an array of parameters as described in the regular expression.
Now let’s see the middlewares, that thing where you can place code that will be always executed before the completion of the response.
Still here? Well done and thank you!
We’ve covered the basic pieces of a PHP Web Service; maybe the bones for your next lean REST API :-)
If you are not fully satisfied, though, and you crave to go deeper… the whole solution (with some extras such as helpers and configurations) is waiting for you on this repository.
In case you need it, feel free to bug us here or on other channels; we are more than happy to give a helping hand!
Enjoy and don’t forget to make a clap if you liked it! Easy peasy!