A PHP WebService for the minimalist ones

Marcello Barile
Mar 10, 2018 · 3 min read

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

> 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.
e.g.:
“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?

How to apply a common logic to the routes

Now that we know the theoretical domain, let’s move into coding

Our router function

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.

A couple of routes

Now let’s see the middlewares, that thing where you can place code that will be always executed before the completion of the response.

Two middlewares

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!

JustCodeBlog

The perfect place for programmers and software engineers…

JustCodeBlog

The perfect place for programmers and software engineers who want to have a glance over what they love most … coding.

Marcello Barile

Written by

A computer scientist who works on a daily basis with TypeScript and Node.js, passionate about Computer Vision and Robotics.

JustCodeBlog

The perfect place for programmers and software engineers who want to have a glance over what they love most … coding.