views:

2460

answers:

4

I've got a PHP application I wrote earlier that I'd like to add a RESTful API to. I'd also like to expand the site to behave more like a Rails application in terms of the URLs you call to get the items in the system.

Is there any way to call items in PHP in a Railsy way without creating all kinds of folders and index pages? How can I call information in PHP without using a GET query tag?

+6  A: 

If you have some form of mod_rewrite going you can do this quite easily with a .htaccess file.

If you have something like this:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

It will check that the file you are trying to access doesn't exist already. (Say you had a file hello.html that you still needed people to access via http://yoursite.com/hello.html)

Then if the file doesn't already exist it will load your index.php file with the rest of the URL stored in the url variable.

This means you can call something like this http://yoursite.com/pages/edit/24 and it will load index.php with /pages/edit/24 inside the url variable.

That should get you started and you won't need all kinds of folders and index pages, just mod_rewrite, .htaccess file and an index.php that will be used to load whatever you need.

xiaohouzi79
+2  A: 

You also might consider to use one of the PHP frameworks with built-in REST support, for example CakePHP.

dhofstet
A: 

Easiest way would probably using a framework that provides you with REST-oriented functionnalities. I know Zend Framework does that, with the class Zend_Rest_Server, that allows easy creation of a REST server.

I suppose many other frameworks do just the same.

But, if you already have an application that doesn't use a framework (or that is based on a Framework that doesn't embed that kind of class), a couple of URLrEwriting rules would do just fine ; you'd just have a bit more work to map URLS/parameters to classes/methods :-(

Pascal MARTIN
+2  A: 

Quick note in respopnse to Pascal MARTIN: Zend_Rest_Server has absolutely nothing to do with REST. They just do RPC with slightly nicer URLs and call it REST so that it's more trendy.

If you want to do REST, you'll need to do a bit more work yourself as I have not found a good REST library for PHP yet. So inspect $_SERVER['REQUEST_METHOD'] to decide what to do with the called resource, etcetera.

skrebbel
Ah i was wrong: CakePHP does in fact to REST pretty nicely. It's got a horrible ORM layer though, but ok :-)
skrebbel