Matt Smithies
Matt Smithies

Reputation: 36

REST with PHP how to map the URL to the backend database

I have been using the REST tutorial http://www.gen-x-design.com/archives/create-a-rest-api-with-php/

I don't understand how the Url in the address bar can be mapped to the database(xml/sql) to output a specific object with its attribute.

So if the address bar had 'localhost/people/1' how can it be linked to the database to extract the relevant information using rest so the query would be "SELECT * FROM people where id=".$id=1.

A coded example with a breakdown of the theory would be fantastic

Thanks

Upvotes: 1

Views: 970

Answers (1)

Jeremy Harris
Jeremy Harris

Reputation: 24549

If by "output a specific object with its attribute" you mean a literal PHP object, it would involve serialization and whatnot, but I don't think that is what you are looking for. Instead, to get a set of data from a database by making a REST request, this is roughly how the flow would work:

  1. REST request is received using GET

  2. Application parses parameters from URL

  3. Application queries database using parameters

  4. Application formats data to return in a particular format, usually JSON or XML.

  5. Application returns data to caller

As far as mapping to a database, this has more to do with the technique used for serving data. The most common technique is called Object-Relational Mapping and there are many popular ORM's for PHP that implement this well such as Doctrine.

The URL and method in your REST request provides parameters and instructions on what do do (GET, POST, DELETE, etc). Once you have those things, it should be fairly simple to create application logic to connect those parameters with your ORM, receive the data, format it, and return it.

[EDIT] I suppose I am generalizing a little with the above discussion. REST works much easier using an MVC pattern (as in the tutorial you linked to). In this way, the URL api.somesite.com/user/show/1 translates to:

  • Controller: user
  • Action: show
  • Parameter: 1

The controller is a file that contains methods called actions. The parameter is passed to the action method where it can be used.

Furthering the MVC paradigm, your Models will handle connections do the database. Depending on your style, the model may be a "fat model" and you will do all your input filtering/validating as well as output formatting their.

To answer your question in the comment, the "parsing" is usually done via a Routing functionality which breaks down the URL and sends the request to the proper controller/action.

Upvotes: 1

Related Questions