PHP + Ruby with ActiveRecord 範例
如果老闆要求使用php,可是您卻是Ruby狂熱者,這.. 怎辦呢?
沒關係! 一樣用Ruby寫,php只要做一點點的處理就好!
How to? php中有這個函式:exec
( 本範例實作於Windows XP Professional搭配InstantRails;在其他作業系統上沒有測試過,不過各位還是可以嘗試看看 )
我們來試試看吧!
先寫個test.rb:
#!/usr/bin/env ruby
#
# Filename: test.rb
#
puts "Hello"
puts "world"
再寫個test.php:
<?php
exec("test.rb", $args);
foreach($arg as $args)
echo $arg . "<br />";
?>
將兩個檔案放在同一個目錄下後,打開瀏覽器瀏覽test.php;看!是不是顯示結果出來了?
OK,我們直接來用ActiveRecord幫我們新增資料吧!
我們需要一張普通頁面、一張php網頁跟一個ruby檔案:
#!/usr/bin/env ruby
#
# Filename: ar.rb
#
require 'rubygems'
gem 'activerecord'
ActiveRecord::Base.establish_connection(
:adapter => 'mysql',
:host => 'localhost',
:username => 'root',
:password => '',
:database => 'cal'
)
class Event < ActiveRecord::Base;end
name, descr = ARGV[0], ARGV[1]
puts Event.new({:name => name, :descr => descr, :date => Date.today, :time => Time.now}).save
好了,接下來是普通頁面,這是送出表單:
<!-- Filename: ar_form.html -->
<html>
<head>
<title>PHP with Ruby and ActiveRecord</title>
</head>
<body>
<form action="ar_save.php" method="POST">
Username: <input type="text" name="usrname" /><br />
Description: <textarea name="descr"></textarea><br />
<input type="submit" value="Save it!" />
</form>
</body>
</html>
這是php網頁:
<?php
// Filename: ar_save.php
exec("2.rb " . $_POST["usrname"] . " " . $_POST["descr"], $arg);
if($arg[0]) echo "Success!";
?>
OK,讓我們來試試看吧!
Look!! It works!!
現在,我們來寫個ar_read.rb跟ar_read.php來讀取資料吧:
# Filename: ar_read.rb
require 'rubygems'
gem 'activerecord'
ActiveRecord::Base.establish_connection(
:adapter => "mysql",
:host => "localhost",
:username => "root",
:password => "",
:database => "cal"
)
class Event < ActiveRecord::Base;end
events = Event.find(:all, :conditions => "name = '#{ARGV[0]}'")
events.each{ |event|
puts event.name
puts event.descr
puts event.date.to_s(:db)
puts event.time.strftime("%H:%M:%S")
}
<?php
// Filename: ar_read.php
exec("ar_read.rb " . $_GET["name"], $args);
$info = array();
for($i=0, $j=0;$i<count($args);$i+=4, $j++){
$info[$j]["name"] = $args[$i];
$info[$j]["descr"] = $args[$i+1];
$info[$j]["date"] = $args[$i+2];
$info[$j]["time"] = $args[$i+3];
}
for($j=0;$j<count($info);$j++)
echo "Name => " . $info[$j]["name"] . "<br />Description => " . $info[$j]["descr"] . "<br />Date => " . $info[$j]["date"] . "<br />Time => " . $info[$j]["time"] . "<br />";
?>
看看結果,hmmm.. 看起來真棒!
嗯?如何?Ruby + ActiveRecord的威力很強大吧?
為什麼不要直接用PHP寫就好? 因為光寫SQL你就想跳樓,何必呢?
記住,在Ruby的檔案中,不可以用:
puts 1, 2, 3
這種方法,會造成php收不到回傳,因此必須用這種寫法:
puts 1
puts 2
puts 3
或者就是:
puts 1; puts 2; puts 3
端看個人喜好囉!
沒有留言:
張貼留言