日期:2011-10-13  浏览次数:20391 次


如果老闆要求使用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,讓我們來試試看吧! 本文链接http://www.cxybl.com/html/wlbc/Php/20120607/28694.html