#native_company# #native_desc#
#native_cta#

PHP and Adobe Flex

By Daniel Williams
on September 26, 2008

For those of us that remember the days when we had to employ unconventional means to force Flash / Actionscript to collaborate with PHP, you will be delighted by the introduction of Adobe Flex. Furthermore, if you’re already using Eclipse, you’ll be excited to know that there is an Adobe Flex plugin for Eclipse.

Unlike HTML and the endless number of limitations it presents, Adobe Flex provides an intuitive environment with a vast number of options. There is a large variety of events and styles that far exceed what is available with custom coding in Javascript and CSS. The only caveat is that a current instance of Adobe Flash plugin is required on the client’s browser.

The purpose of this article is not to familiarize you with Adobe Flex, but to demonstrate its integration with PHP.

Brief Sample of Flex
To demonstrate the development process in Adobe Flex, we’ll begin with a simple ‘Hello World’ example. If you’re already familiar with XML and Flash, you’re already ahead in the game. Using the IDE, Flex or Eclipse, we will create an app. The project includes many files, but we’re going to focus particularly on the file that has a *.mxml file extension. You will be presented with two development views, a ‘Source’ and ‘Design’ view. The Design view is a WYSIWYG that constructs our *.mxml file. The Source view is the *.mxml file editor. You’ll notice that the *.mxml file is an XML structured file (see Example 1).
Example 1

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute"
	currentState=" formContent">

<mx:states>
	<mx:State name="formContent">
		<mx:AddChild position="lastChild">
				<mx:Button x="150" y="150" 
	label="Click Me!" 
	click="currentState='resultsPage';"/>
		</mx:AddChild>
	</mx:State>
	<mx:State name="formResults">
		<mx:AddChild position="lastChild">
			<mx:Label x="150" y="150" text="Hello World!"/>
		</mx:AddChild>
	</mx:State>
</mx:states>

</mx:Application>

A Flex app can have one or more views, or states. Our example app includes two states, formContent and formResults. The state formContent contains one child element, a button labeled, “Click Me!” Alternatively, we have another state called, formResults. This state will display a label with the text, “Hello World!” You may notice that the tag, mx:Application includes an attribute called, currentState, with a value of “formContent”. This instructs the app to display the state formContent by default.

When testing the app, you’ll notice that when you click the button, the state of the app changes to the ‘Hello World’ label. Using this design, we will now connect to a PHP script to acquire data for display.

PHP Integration
To some, the biggest cost benefit of the Flex / PHP relationship is the database interaction. Let’s assume that we have a MySQL database table called, “T_STATES”. The table includes two columns, “STATENAME” and “ABREV”. Our PHP script will query this table and present the results in XML (see Example 2.1).
Example 2.1

<?php

// connect to database
$db = mysqli_connect(127.0.0.1,"test","password","STATEDB");
 
// alter header for XML output
header("Content-type: application/xml");

// begin XML root tag
echo "<RESULTS>rn";

// query table for table
$res = mysqli_query($db,"SELECT STATENAME, ABREV FROM T_STATES");

// return results
while( $data = mysqli_fetch_array($res) )
{
	echo "t<STATE ABV="".$data[1]."">";
	echo $data[0]."</STATE>n";
}

// close root tag of XML
echo "</RESULTS>rn";

// close database
mysqli_close($db);

?>

Now that our PHP script returns the results we want, we must configure our Flex app to retrieve the results. Using our Flex example, we are going to add a network service connection (mx:HTTPService) to retrieve our PHP-generated XML file. These results will then be displayed on our formResults state (see Example 2.2). You may notice that the button will trigger the network service, which calls to our function, showResults(). This function will loop through our PHP-generated XML and populate the textbox component on the formContent state.
Example 2.2

<?xml version="1.0" encoding="utf-8"?>
<mx:Application
	xmlns:mx="http://www.adobe.com/2006/mxml"
	layout="absolute"
	currentState="formContent">

	<mx:HTTPService id="sendForm"
		result="showResults(event)"
		resultFormat="object"
		url="form.php" />

	<mx:Script> 
	<![CDATA[
        
	import mx.rpc.events.ResultEvent;
        	
	// function to handle results
	public function showResults(evt:ResultEvent) : void
	{
		var retResult:Object = evt.result; // data returned as object 
		var resData:String = ''; // string used to populate results
		
		currentState='resultsPage'; // change state
            	
		// loop through result set and populate results string
		for( var i:Number=0; i < retResult.RESULTS.STATE.length; i++ )
		{
			resData += retResult.RESULTS.STATE[i]+
				' ('+retResult.RESULTS.STATE[i].ABV+')n';
		}
	            
		resText.text = resData; // display results
	}
            
	]]> 
	</mx:Script> 

	<mx:states>
		<mx:State name="formContent">
			<mx:AddChild position="lastChild">
				<mx:Button x="150" y="150" label="Click Me!" 
					click="sendForm.send();"/>
			</mx:AddChild>
		</mx:State>
		<mx:State name="formResults">
			<mx:AddChild position="lastChild">
				<mx:Label id="resLabel" x="150" y="150" text="Results"/>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:TextArea id="resText" x="150" y="175" width="300" height="200"/>
			</mx:AddChild>
		</mx:State>
	</mx:states>
	
</mx:Application>

Building a Dynamic Chart
As an additional option available for Flex, Adobe has offered chart components to complement your apps. Without going into great detail, we will now demonstrate its use with our example app. In Example 3.1, we are going to add additional column called, “POPULATION”, to our database and return the data in our PHP script.
Example 3.1

<?php

…

// query table for table
$res = mysqli_query($db,"SELECT STATENAME, ABREV, POPULATION FROM T_STATES");

// return results
while( $data = mysqli_fetch_array($res) )
{
	echo "t<STATE ABV="".$data[1]."" POP="".$data[2]."">";
	echo $data[0]."</STATE>n";
}

…

?>

Next, we must add the chart to our app (see Example 3.2).
Example 3.2

<mx:State name="formContent">
			<mx:AddChild position="lastChild">
				<mx:Label id="resLabel" x="150" y="150" text="Results"/>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:TextArea id="resText" x="150" y="175" width="300" height="77"/>
			</mx:AddChild>
			<mx:AddChild position="lastChild">
				<mx:ColumnChart x="150" y="260" id="colchart" 								dataProvider="{popChart}" width="300" height="300">

					<mx:horizontalAxis>
						<mx:CategoryAxis categoryField="State"/>
					</mx:horizontalAxis>
		                
					<mx:series>
						<mx:ColumnSeries xField="State" yField="Pop"
							 displayName="Pop"/>
					</mx:series>
				
				</mx:ColumnChart>
			</mx:AddChild>
		</mx:State>