Thursday March 20, 2008
Activeresource to a none rails site
Lately I've been getting into rails, what can I say its a nice clean language. I also run a forum, its a forum written in php. Now I want to build apps for my php (vbulletin) forum, but I didn't want to do cross site database calls. I wanted my plug ins to be as independent as possible from the main vbulletin app..
In another website I've been writing, there are three components that interconnect to each other using activeresource! Since it was so easy to implement I thought I'd give it a go cross programming language! Heres how I did it!
First in PHP create your restfull program!
I called mine rest.php :) I know very original!
Using a sexy XML library I created for php. From this simply class, I can easily create from a select from a database my xml!
<?php
$userid = $_GET['user'];
$result = $db->query_read("select userid, username, email from user where userid = '$userid' ");
$count = mysql_num_rows($result);
$xml = new XmlBuilder();
$xml->filename("user.xml");
for($i=0; $i<$count; $i++) {
$user = $db->fetch_array($result);
$xml->openTag("user");
foreach ($user as $tag => $value) {
$xml->addfield($tag, $value);
}
$xml->closeTag();
}
echo $xml->build();
?>
So far so good! So if we go to file.php?user=1 we should get the user with id 1.. You could add all sorts of cool things here. But this is just an example to get you guys going.
Now finally ensure you have mod_rewrite working in apache! now if your php file is called rest.php, you'll need this rewrite rule to make the magic happen
RewriteRule ^/rest/users/(.*) /rest.php?user=$1
In your rails app, now create a model named User, e.g. models/user.rb, and add
class User < ActiveResource::Base
self.site = "http://domain.com/rest/"
end
and don't forget your corresponding controller. This will now fetch all requests from our rest.php file. If you need any help, please drop me a line!
Back
