ZEND+FLEX认证+收藏

来源:互联网 发布:win10自带c语言 编辑:程序博客网 时间:2024/05/16 18:09

http://corlan.org/2008/11/13/flex-and-php-remoting-with-zend-amf/   ZEND+FLEX收藏

 

http://www.keithcraigo.com/archives/66ZEND+FLEX认证

http://www.keithcraigo.com/archives/181ZEND+FLEX认证

 

http://ressources.mediabox.fr/tutoriaux:flashplatform:dynamique:remoting:zendlogin:zendlogin1ZEND+FLEX认证

 

 

Flex and PHP: remoting with Zend AMF

The latest PHP library to add support for AMF and remoting is Zend Framework. The preview prelease version 1.7offers a new component Zend_AMF that lets you create Flex applicationsthat talk to PHP backends using remoting. Since I am a big fan ofremoting as a way to get data to your Flex/AIR clients, I wanted to adda short post explaining how to use it. Here is another post I wrote on remoting with AMFPHP. Actually this post is a part of a larger article I did for Adobe Developer Connection. I want to keep it more focused, so I wrote this one.

You can download a Flex Builder project that contains the code I explain in this article from here. Inside of the archive you will find a readme.txt file explaining what to do with it.

Installing the Zend Framework

After downloadingthe Zend Framework 1.7 archive, extract the files. Next, you have toadd the library folder to your PHP include path. Open the php.ini fileand add the path to the library folder to the include_path; on mymachine looks like:
include_path = “c:htdocszend_frameworklibrary”

Next, save the file and restart your web server. You can read more about installing Zend Framework here. With this, you’ve completed the “installation” of Zend Framework.

What is AMF and remoting and why should you use it?

If you already know these answers, you may want to skip to the nextsection. Let’s start by understanding remote procedure calls. Remoteprocedure calls let Flex applications  make direct calls on the methodsof your server side classes. Using BlazeDS or LiveCycle Data Servicesyou can expose your Java and ColdFusion classes to the Flexapplication. However, if you use PHP you need a third party library onthe server to expose PHP classes directly. Existing solutions includeZend AMF, WebORB, and AMFPHP. This article focuses on remoting withZend AMF. AMF is a binary protocol for serializing the messages.Because it is binary, it is more efficient in terms of bandwidth andserver processing load than JSON or XML methods. If you want to see foryourself how much more efficient it is, James Ward has put together anice benchmark.

Zend AMF is a PHP library that knows how to serialize anddeserialize the AMF protocol (it is part of the Zend Framework startingwith version 1.7), and thus lets you expose PHP classes to Flexapplications. Another compelling reason for using remoting is codereuse. Because you can call methods on PHP classes and these methodscan return PHP objects, you don’t have to modify your existing code tooutput JSON or XML.

As I noted earlier, Zend AMF remoting uses AMF to serialize messagesbetween the server and Flex client. It also offers the ability to mapan ActionScript class to a PHP class. For example, suppose you want todisplay in Flex the information from a table with the followingstructure:

contacts
-------------------------------
id primary key int
name varchar(255)
email varchar(255)

When using remoting, you create an ActionScript class to model thisdata in the client and a PHP class to model the same data on theserver. When you create the PHP class that you want to call from Flex,you add a method that, for example, retrieves all the contacts from thetable. This method will return an array of PHP VO classes, and in Flexyou will get an array of ActionScript objects. All the conversions fromPHP objects to AMF to ActionScript objects are done automatically foryou by  Flex and Zend AMF.

When you use XML or JSON for remoting, you’ll tipically need extrasteps in Flex to process the data in order to display or store it.

Let’s look at a working example.

Create the Flex PHP project

Usually, when I work with Flex and PHP projects, I prefer to use Flex Builder and Zend Studio installedtogether. It is possible, however, to work with Flex Builder and a PHPplugin to help you with the PHP code. Either way, you should create aFlex project that uses PHP on the server side (if you plan to use ZendStudio and Flex Builder, first create a Zend PHP Project, then use theAdd Flex Nature wizard to add Flex PHP nature on the project). This wayyou streamline the deployment of the SWF file (the compiled result ofthe Flex project) to the PHP server. I chose to create a new projectcalled “flex_php”.

Next, create a folder inside the PHP server root named“zendamf_remote”, and add this folder to the project. Choose New >Folder, and then click on the Advanced button. If you want to have thesource files for the Zend Framework available to your project, and youuse Zend Studio too, then open the properties page for the project, goto the PHP Include Path > Libraries tab, and add an External Folderpointing to the place where the Zend Framework is installed.

Create the PHP code

In the “zendamf_remote” folder, create three PHP files:MyService.php, VOAuthor.php, and index.php. Open the MyService.php pageand paste the following code (you need to update the connectioninformation for your specific database setup; to do this, look for thefour constants at the top of the class):

<?php
require_once('VOAuthor.php');
//connection info
define("DATABASE_SERVER", "localhost");
define("DATABASE_USERNAME", "mihai");
define("DATABASE_PASSWORD", "mihai");
define("DATABASE_NAME", "flex360");

class MyService {
/**
* Retrieve all the records from the table
* @return an array of VOAuthor
*/
public function getData() {
//connect to the database.
//we could have used an abstracting layer for connecting to the database.
//for the sake of simplicity, I choose not to.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
//retrieve all rows
$query = "SELECT id_aut, fname_aut, lname_aut FROM authors_aut ORDER BY fname_aut";
$result = mysql_query($query);

$ret = array();
while ($row = mysql_fetch_object($result)) {
$tmp = new VOAuthor();
$tmp->id_aut = $row->id_aut;
$tmp->fname_aut = $row->fname_aut;
$tmp->lname_aut = $row->lname_aut;
$ret[] = $tmp;
}
mysql_free_result($result);
return $ret;
}
/**
* Update one item in the table
* @param VOAuthor to be updated
* @return NULL
*/
public function saveData($author) {
if ($author == NULL)
return NULL;
//connect to the database.
$mysql = mysql_connect(DATABASE_SERVER, DATABASE_USERNAME, DATABASE_PASSWORD);
mysql_select_db(DATABASE_NAME);
//save changes
$query = "UPDATE authors_aut SET fname_aut='".$author->fname_aut."', lname_aut='".$author->lname_aut."' WHERE id_aut=". $author->id_aut;
$result = mysql_query($query);
return NULL;
}
}
?>

This is the class you will call from Flex. It has two methods: oneto get all the records from the table, and another to update the valuesfor one record.

Let’s create the code for the Value Object, the data model. This isused by the MyService class to wrap one row from the table. Thus, themethod getData() returns an array of VOAuthor, and the method saveData() receives one argument: the VOAuthor of the row that was changed. Open the file VOAuthor.php and add this code:

<?php
class VOAuthor {
public $id_aut;
public $fname_aut;
public $lname_aut;
}
?>

As you can see, this class is very simple; it just provides the samemembers as the fields from the table. Finally let’s create the code forindex.php file. This is the plumbing code that expose the MyServiceclass to Flex clients with the help of the Zend AMF. Add the followingcode:

<?php
require_once('Zend/Amf/Server.php');
require_once('MyService.php');

$server = new Zend_Amf_Server();
//adding our class to Zend AMF Server
$server->setClass("MyService");
//Mapping the ActionScript VO to the PHP VO
//you don't have to add the package name
$server->setClassMap("VOAuthor", "VOAuthor");
echo($server -> handle());
?>

I use an instance of Zend AMF server to create a PHP end point thatcan be called from Flex. Then I register the MyService class to theserver, thus I can call this class from Flex. And finally I map theActionScript data model (VOAuthor) to the PHP VOAuthor data model.

When you use remoting, you get the casting of the data to the right type for free. For example, MyService.getData()method returns an array of VOAuthor PHP objects. However, as you willsee later, in Flex the result is an array of VOAuthor ActionScriptobjects.

Creating the Flex application

Now that you have the PHP code in place, you are ready to create theFlex code that will call the PHP class. I want the Flex application tohave a button that gets the data from the server, uses a data grid todisplay the data, and enables the user to edit any cell (except ids)within the data grid. Whenever a cell is edited, the update is sentautomatically to the server and saved to the database as well.

First, be sure to select the Flex perspective from the top right icons of Eclipse.

The next thing you need to do is to create a configuration file thatFlex can use to reach the PHP service. Create the fileservices-config.xml in the root of the project. Open the file and addthis code:

<?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/zendamf_remote/" class="flex.messaging.endpoints.AMFEndpoint"/>
</channel-definition>
</channels>
</services-config>

Be sure to check the endpoint node (at the bottom of the file); yourURL to the zendamf_remote folder might be different. Set the valueappropriately for your setup.

Now you need to tell Flex Builder to use this file when compilingthe project. Right click on the project name in the Project Explorerand choose Properties. Select Flex Compiler and add the following toAdditional compiler arguments field: -services“absolute_path_to_the_file/services_config.xml”:

Adding services_config to compile arguments

You will use a RemoteObject to communicate with the server, so add a mx:RemoteObjecttag. You need to set the source attribute to MyService (this is the PHPclass name) and the destination to zend – this is the destinationcreated in the services-config.xml file. Also give a name to thisobject by adding an id attribute and set it to myRemote. Set theattribute showBusyCursor to true (whenever a call is madethis will render the mouse icon as a watch, until a response from theserver is received). The code should look like this:

<mx:RemoteObject id="myRemote" destination="zend" source="MyService" showBusyCursor="true">
</mx:RemoteObject>

Now you need to declare the methods you want to call on the PHPclass, and add the listeners for fault and result events. The code is:

<mx:RemoteObject id="myRemote" destination="zend" source="MyService" showBusyCursor="true" fault="faultListener(event)">
<mx:method name="getData" result="getDataListener(event)"/>
<mx:method name="saveData" result="saveDataListener(event)"/>
</mx:RemoteObject>

Next you need a UI to make the call to the server and display/editthe data. A button and a data grid will do. Add this code above the RemoteObject code:

<mx:VBox top="30" left="100">
<mx:Button label="Get data" click="{myRemote.getData()}" />
<mx:DataGrid id="myGrid" editable="true" itemEditEnd="save(event)"/>
</mx:VBox>

As you can see, the button calls the getData() method on the remoteObject. The data grid has an event listener registered for the itemEditEnd event.

The last step is to create the listeners you declared. For this, add an mx:Script tag to your MXML application and define four functions in it:

<mx:Script>
<![CDATA[
import mx.controls.dataGridClasses.DataGridColumn;
import mx.events.DataGridEvent;
import org.corlan.VOAuthor;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.collections.ArrayCollection;
/**
* listener for the data grid's itemEditEnd event
*/
privatefunction save(event :D ataGridEvent):void {
//we don't want to update the id of the item
if (event.dataField == "id_aut") {
event.preventDefault();
return;
}
//retrieve the new value from the item editor instance
var dataGrid:DataGrid = event.target as DataGrid;
var col:DataGridColumn = dataGrid.columns[event.columnIndex];
var newValue:String = dataGrid.itemEditorInstance[col.editorDataField];
//retrieve the data model that was edited
var author:VOAuthor = event.itemRenderer.data as VOAuthor;
// if the value wasn't change, exit
if (newValue == author[event.dataField])
return;
//update the model with the new values
author[event.dataField] = newValue;
//call the remote method passing the data we want to be saved
myRemote.saveData(author);
}
/**
* Result listener for get data operation
*/
privatefunction getDataListener(event:ResultEvent):void {
//set the result array as data provider for the data grid
myGrid.dataProvider = event.result as Array;
}
/**
* Result listener for save data operation
*/
privatefunction saveDataListener(event:ResultEvent):void {
Alert.show("The data was saved!");
}
/**
* Fault listener for RemoteObject
*/
privatefunction faultListener(event:FaultEvent):void {
Alert.show(event.fault.message, "Error");
}
]]>
</mx:Script>

Finally, you need to create the ActionScript Value Object that willact as a data model for the data sent from PHP. Right-click on the srcfolder from Flex Navigator, and choose New > ActionScript class. Forthe package type org.corlan, and for the name type VOAuthor. Click OK. Now it is time to add the members and some meta-data:

package org.corlan {
[RemoteClass(alias="VOAuthor")]
[Bindable]
publicclass VOAuthor {
publicvar id_aut:int;
publicvar fname_aut:String;
publicvar lname_aut:String;
}
}

The RemoteClass meta-data is very important. This tells to theActionScript that the remote class (the one from PHP) that it maps tois called VOAuthor. If you forget this or you misconfigure it, you willget generic objects in ActionScript instead of VOAuthor, andassociative arrays in PHP instead of VOAuthor.

You are done. There shouldn’t be any errors.

Now you are ready to test the code. Start the Flex application byclicking Run in the toolbar. When the application opens in your defaultbrowser, click the Get data button. You should see the data gridpopulated with some data:

Testing the application

To edit the items, just double click on any name and changesomething. When you finish editing, click outside the data grid. Thechanges will be sent to the server. If you don’t believe me, just go tothe database and view the records.

Editing a cell

That’s it people!

原创粉丝点击