I have been reading the article:
http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
to learn how to build a rest API. At one point it says "Assuming you’ve routed your request to the correct controller for users"
I have been trying to find a tutorial or something that shows how to do this, but everything i have read suggests a framework. How can i do this without a framework?
EDIT:
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 dont 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.
Cheers
I think this is a matter of terminology. Every code with some level of generalization can be called "framework". And since you're asking about "routing", which provides a starting level of generalization, every implementation becomes a framework.
If you don't want to use existing fully-fledged frameworks, you can elaborate your own light-weight-implementation. Here is some articles to start:
- Write your own PHP MVC framework
- PHP MVC framework in one hour
(the author has decided to remove this post because he thinks that using a modern fully-fledged framework is more appropriate way of programming such things, yet some people find such simple and stripped-down approache more suitable in many aspects: learning, efficiency, no huge dependencies, etc); the post is available on some other sites, for example, in the wayback machine or copies
- The Model View Controller in PHP
All these intros include explanations of the routing mechanizm and demonstrate its implementation.
Basically, a router is a kind of internal "DNS" (in a figurative sense) inside your application. When a request arrives to your site, you need to dispatch it to appropriate worker class, according to that request properties. This is the router's task.