I have been reading the article to learn how to build a rest API:
http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
At one point it says "Assuming you’ve routed your request to the correct controller for users"
How can I do this without a framework?
I am writing a REST API that I can interact with from a different application. I ready the tutorial above, and it makes sense mostly, but I don't exactly understand what it means to route my request to the correct controller for users.
Assuming you are using Apache
, you can accomplish this easily using a combination of mod_rewrite
and some PHP-based logic. For example, in your .htaccess
or vhost definition, you could route all requests through a single handler, possibly index.php
:
# Don't rewrite requests for e.g. assets
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*+)$ index.php?q=$1 [L]
...then in your index.php file do something like:
$target = $_REQUEST['q'];
/* parse the request and include the appropriate controller PHP */
For example, a request for /products/1234
might result in a controllers/products.php
handler being included. That handler could then act on product 1234
. Because you're using REST, you shouldn't need to be concerned with the original request having a query string parameter.
There are multiple ways to accomplish what it sounds like you're trying to do, this is just one of them. Ultimately what you go with will depend on what your specific requirements dictate. The above pattern is fairly common however, many frameworks use it or something like it.
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