10월 292010
 

인터넷을 아무리 돌아다녀도 Flex Builder없이 Flex 3와 PHP를 통합하는 방법에 대해 설명해 놓은 것을 찾기 어려웠는데, 아래 링크의 글을 보고 Flex Builder없이 오픈 소스인 FlashDevelop을 이용해 둘을 통합해 봤습니다.


준비물


FlashDevelop 3.3.1
Flex 4 SDK
ZendAMF 1.10.8
Wamp Server (Apache + PHP + MySql)

ZendAMF 란

ZendAMF 는 Adobe Flex, Flash와 php가 서로 자료를 교환을 할 수 있도록 하기 위해 php로 새로이 구현된 Action Message Format (AMF)이다. 예전엔 amfPHP라고 있었으나 ZendAMF가 새로운 것이라 여기서 사용토록 하겠다. 무료로 다운로드 받을 수 있는 프로그램이고, 여기서 사용할 ZendAMF는 1.10.8 버젼이다.


AMF 란…

AMF 는 원격지 프로시져 호출을 이용하는 바이터리 프로토콜로 Adobe Flash, Flex와 다른 많은 언어로 된 서버측과 데이터베이스를 연결토록 해준다.

시작해보자

기본적으로 WampServer를 C:\amp 디렉토리에 설치를 했다고 가정합니다. 
FlashDevelop과 Flex 4 SDK를 설치하고 설정하는 것은 인터넷에 꽤많이 있으니 이 글에서 설명은 하지 않겠습니다.


ZendAMF 설치

다음에 해야 할 것은 웹 서버의 htdocs 디렉토리로 가야 합니다. 만약 WampServer를 기본 디렉토리아 설치를 했다면, 기본 위치는 C:\wamp\www 가 될 것입니다. 여기에 다운로드 받은 ZendAMF.zip 파일의 압축을 해제합니다. 그렇게 되면 C:\wamp\www\ZendAMF-1.10.8 가 생기게 되는데, 그 아래 library 폴더가 있을 것이고, 그 아래 Zend 폴더가 있는데, 이 “Zend” 폴더를 C:\wamp\www 아래로 복사 해 넣습니다. (C:\wamp\www\Zend
). 이게 다 입니다. 따로 설정같은 것은 필요없습니다.


ZendAMF php파일 2개 만들기

c:\wamp\www 디렉토리 아래 zend_gateway.phptest_class.php 파일 2개를 만듭니다. 이 두개는 서로 다른 기능을 합니다. zend-gateway.php는 Flex로 통하는 통로 역할을 하는데, 이를 통해 Flex가 이 파일을 통해 모든 AMF 클래스 (여기서는 test_class.php) 를 찾을 수 있도록 해줍니다.
아래의 코드는 zend_gateway.php에 넣어 줍니다.

<?php
    error_reporting(E_ALL | E_STRICT);  //optional
    require_once “Zend/Amf/Server.php”; //the zendAMF server
    require_once “test_class.php”;  //our test class
    $server = new Zend_Amf_Server(); //declare the server
    $server->setClass(“test_class”); //load our test-class
    echo($server->handle()); // needed to start the server
?>

test_class.php 파일에는 클래스와 함수들을 넣을 것입니다. 이 함수들은 Flex에서 원격 객체를 이용해 불려집니다.

<?php
class test_class {
public function __construct() {
//this function is needed, is the constructor of class!!
}

public function sayHello($user=NULL) {
if($user==NULL) return ‘Hello anonymous user! This is php saying hello!’;
else return ‘Hello ‘.$user.’! This is php saying hello!’;
    }
}
?>

Flex 4 파일 설정

일단 php 파일을 모두 만들었으면, 이제는 Adobe Flex 컴파일러에게 zend_gateway.php 라는 게이트웨이를 식별하도록 하고, Flex에서 원격 호출을 할 수 있도록 합니다. 이를 위해 services-config.xml를 만들어서 컴파일러가 같이 읽어오도록 합니다.
아래의 내용으로 services-config.xml를 만들고, php 파일이 있는 C:\wamp\www 에 저장 합니다.

<?xml version=”1.0″ encoding=”UTF-8″?>
<services-config>
    <services>
        <service id=”amfphp-flashremoting-service” class=”flex.messaging.services.RemotingService” messageTypes=”flex.messaging.messages.RemotingMessage”>
            <destination id=”zend”>
                <channels>
                    <channel ref=”my-zend”/>
                </channels>
                <properties>
                    <source>*</source>
                </properties>
            </destination>
        </service>
    </services>
    <channels>
        <channel-definition id=”my-zend” class=”mx.messaging.channels.AMFChannel”>
            <endpoint uri=”http://localhost/zend_gateway.php” class=”flex.messaging.endpoints.AMFEndpoint”/>
        </channel-definition>
    </channels>
</services-config>

Flex 4 파일을 만들자.

이제 Flex파일을 만들어 보겠습니다. ZendAMFTest.mxml 에 몇몇 시각적인 요소들을 추가합니다. 이 파일의 경우 간단한 몇몇 패널과 아이템, 3개의 함수를 만들것입니다. 하나는 php 함수를 호출하기 위한 것이고, 다른 하나는 성공적인 답을 얻었을 경우를 처리하는 것, 세번째는 에러 상황을 처리하는 것입니다.

<?xml version=”1.0″ encoding=”utf-8″?>
<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute”>
<mx:Script>
<![CDATA[
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.controls.Alert;

private function onSayHelloResult(evt:ResultEvent):void {
Alert.show(evt.result.toString(),”DONE!”);
}
private function onError(err:FaultEvent):void {
Alert.show(err.message.toString(),”ERROR!”);
}
private function callZend():void {
zendAMF.sayHello.arguments.user=userName.text;
zendAMF.sayHello();
}
]]>
</mx:Script>
<mx:Panel width=”361″ height=”222″ layout=”absolute” title=”Adobe Flex and PHP integration using ZendAMF” horizontalCenter=”0″ verticalCenter=”0″>
<mx:Label x=”26″ y=”53″ text=”Enter your name : “/>
<mx:Label x=”144″ y=”90″ text=”AND”/>
<mx:TextInput x=”144″ y=”51″ id=”userName”/>
<mx:Button x=”26″ y=”122″ label=”Call php sayHello() function!” width=”278″ click=”callZend()”/>
</mx:Panel>
<mx:RemoteObject id=”zendAMF” destination=”zend” showBusyCursor=”true” source=”test_class”>
<mx:method name=”sayHello” result=”onSayHelloResult(event)”  fault=”onError(event)”>
<mx:arguments>
<user>
{null}
</user>
</mx:arguments>
</mx:method>
</mx:RemoteObject>
</mx:Application>

위와 같은 파일을 FlashDevelop내에 Flex 4 프로젝트를 만듭니다.

위와 같이 프로젝트를 만들면, ZendAMFTest.mxml 파일이 만들어지고, “src”디렉토리 밑에 maim.mxml이 만들어집니다. 그럼 ZendAMFTest.mxml 파일은 삭제하고, maim.mxml는 우측 마우스 버튼을 눌러서 ZendAMFTest.mxml파일로 이름을 바꿉니다. 그리고 위의 내용을 ZendAMFTest.mxml 파일에 저장을 합니다. 그리고, 위에서 작성한 services-config.xml파일 (C:\wamp\www에 위치)을 FlashDevelop프로젝트 파일이 있는 곳으로 복사해 옵니다.

그럼 아래와 같은 모습이 됩니다.


이제는 컴파일을 해서 ZendAMFTest.mxml을 만들어야 합니다.
이때, Flex컴파일러가 services-config.xml에 외부 서비스가 있다는 것을 인식시키기 위해 컴파일러에 옵션을 추가합니다.

Project –> Properties 메뉴를 선택하면, 다이얼로크 창이 뜹니다. 거기서 “Compiler Options” 탭을 선택하고 그 아래 “Additional Compiler Options” 에 “-services services-config.xml”라고 입력을 하면, 아래와 같은 형태가 됩니다.

“OK” 버튼을 누른후, “F8″키를 눌러 컴파일을 합니다.


자 이제, ZendAMFTest.swf 파일이 bin 디렉토리에 만들어졌고, 이를 C:\wamp\www로 복사합니다.

테스트

인터넷 브라우져로 http://localhost/ZendAMFTest.swf 라고 입력을 하면… 짜잔~~~~

이름에 내용을 넣고 버튼을 누르면 php의 서비스를 통과하여 실행된 내용을 보실 수 있습니다.
내부 구조에 대한 원리와 설명은 생략하겠습니다. 저도 이제부터 공부 좀 해야되거든요…

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)