在以前寫的一篇文章 amfphp 1.0,第一個 Flash Remoting Demo 作了相同的案例可作為比較,如今 Flash Remoting 已不像以前那麼困難,Hello world 是瞭解一個程式語言的捷徑,在這裡重新示範這個入門的 Flash Remoting 案例。
(以下檔案全部要放置於 amfphp/services 目錄之下)
Helloworld.php
<?php
class Helloworld
{
//給 amfphp 參考的 Class 提示
/**
Say Hello
*/
//Function(也是 Method)
function Say($message){
return 'amfphp say:'.$message;
}
}
?>
需特別注意的是 Class 名稱和檔名需一致,不然會得到 Service does not contain any methods 的錯誤提示。建立了 Helloworld.php 之後開啟 amfphp 的 Service Browser,我們可以看到剛剛建立的 Class - Helloworld 已經出現在左方列表,點擊它可以看到關於此 class 的資訊,親切的 amfphp 還提供了 PHP 變數測試,在 message 欄位輸入 Hello world! 並按下 call 按鈕。

但 Flash Remoting 可不是只有 PHP 而已喔,接下來透過 Flash 呼叫這個名為 Helloworld 的 PHP Class 才是重頭戲。
Helloworld_AS3.fla
//定義 nc 為網路連線,res 為回應結果及偵錯
var nc:NetConnection = new NetConnection();
var res:Responder = new Responder(onResult, onFault);
//設定此連線透過 amfphp gateway 連結
nc.connect("http://localhost/amfphp/gateway.php");
//設定此連線呼叫項目: call(PHP Class.Method, 回鷹, 變數內容)
nc.call("Helloworld.Say", res, "Hello world!");
//偵錯函數
function onFault(responds:Object):void{
for(var i in responds){
trace(responds[i]);
}
}
//結果函數
function onResult(responds:Object):void{
trace(responds);
}
以上 AS3 寫在第一影格,因 Flash 會自動產生相關 Class,這裡就不寫 import 的部份了...AS2 的 Flash Remoting 稍有不同,請參考
Helloworld_AS2.fla
var nc:NetConnection = new NetConnection();
nc.connect("http://localhost/amfphp/gateway.php");
nc.call("Helloworld.Helloworld.Say", nc, "Hello world!");
nc.onStatus = function(responds:Object) {
for(var i in responds){
trace(responds[i]);
}
}
nc.onResult = function(responds:Object) {
trace(responds);
}
輸出
到這裡 Hello world 的案例已經是完成了,最後參考了 ActionScript3,請 AS 矩形 Say HelloWorld 這篇文章對 Hello world 加上視覺化的改版修正。
Helloworld_ui.fla
var nc:NetConnection = new NetConnection();
var res:Responder = new Responder(onResult, onFault);
nc.connect("http://localhost/amfphp/gateway.php");
nc.call("Helloworld.Say", res, "Hello world!");
function onFault(responds:Object):void{
for(var i in responds){
trace(responds[i]);
}
}
function onResult(responds:Object):void{
var msg:String = new String(responds);
var mytxt:TextField = new TextField();
mytxt.border = true;
mytxt.text = msg;
mytxt.x = 135;
mytxt.y = 20;
mytxt.width = 130;
mytxt.visible = false;
addChild(mytxt);
createRect(150,150,100,40,2,0x000000,0xFFCC00);
function clickBtn(myMouseEvent:Event):void{
if (mytxt.visible){
mytxt.visible = false;
}else{
mytxt.visible = true;
}
}
function createRect(x1,y1,w1,h1,borderSize,borderColor,bgColor){
var myButton:Sprite = new Sprite();
myButton.buttonMode = true;
addChild(myButton);
var mc:Shape = new Shape();
mc.graphics.lineStyle(borderSize, borderColor);
mc.graphics.beginFill(bgColor);
mc.graphics.drawRect(x1, y1, w1, h1);
mc.graphics.endFill();
myButton.addChild(mc);
myButton.addEventListener(MouseEvent.CLICK, clickBtn);
}
}
懶得寫註解了... 2010/04/13 22:31 |
Trackback Address :: 無法向此文章發送引用