I’m trying to generate rewrite rules for a RESTful API. I just want to see if there is a better way to make this work than having to write out every possible rewrite combination.
Ok so I have 4 query variables to account for in the URL
- Indicator
- Country
- Response
- Survey
The base url will be www.example.com/some-page/ The order of the 4 variables will be consistent but some query variables are optional.
So I could have…
/indicator/{indicator value}/country/{country value}/response/{response value}/survey/{survey value}/
or…(no /response/)
/indicator/{indicator value}/country/{country value}/survey/{survey value}/
or…
/indicator/{indicator value}/country/{country value}/
Is there a better way to accomplish this than filtering the rewrite_rules_array
and adding an array of my rewrite rules manually created? Would add_rewrite_endpoint()
rewrite_endpoint or add_rewrite_tag()
be any use to me?
I think the best option is an endpoint. You get all the data as a simple string, so you can decide how it will be parsed, and you donât have to worry about collisions with other rewrite rules.
One thing I learned about endpoints: keep the main work as abstract as possible, fix the glitches in WordPressâ API in a data agnostic way.
I would separate the logic into three parts: a controller select a model and a view, a model to handle the endpoint and one or more views to return some useful data or error messages.
The controller
Letâs start with the controller. It doesnât do much, so I use a very simple function here:
Basically, it loads the model
T5_CRA_Model
and hands over some parameters ⦠and all the work. The controller doesnât know anything about the inner logic of the model or the view. It just sticks both together. This is the only part you cannot reuse; thatâs why I kept it separated from the other parts.Now we need at least two classes: the model that registers the API and the view to create output.
The model
This class will:
EP_ROOT
I hope the code speaks for itself. 🙂
The model doesnât know anything about the inner structure of the data or about the presentation. So you can use it to register hundreds of APIs without changing one line.
The view
Now we have to do something with our data. We can also catch missing data for incomplete requests or delegate the handling to other views or sub-controllers.
Here is a very simple example:
The important part is: the view doesnât know anything about the endpoint. You can use it to handle completely different requests, for example AJAX requests in
wp-admin
. You can split the view into its own MVC pattern or use just a simple function.