Flash builder 4 Zend-based sitecounter

Introduction

This is a simple example how to create a connection from a Flex movie to a Mysql database using the Zendframework. To develop this project it is best to have a PHP server installed on your computer. I am using MAMP, which is for Mac. Once we have the server installed we create a database and a table for the application. I have named the database “test” and then created the table using a php file. Just execute the file within the server environment and the table will be created automatically.

The PHP part

Here is described how to create a Flex project with PHP and Zend. So I will not further go into details regarding that. Instead I will focus on the Flex file and the PHP file we need in addition and which contains all the functions. When we create our project, which we name “AS3SiteCounter”, we will have a working folder with the name “AS3SiteCounter-debug”, which contains all the files as shown here. The file we focus on first is in the services folder. The name, which you will find in that folder is probably different at the time the project was created. So rename this file to “SitecounterService.php”. Next we will look at the functions we need for our sitecounter.

We need at least two functions, 1. to add all visitor counts and 2. to add only the unique counts. So the first function is shown here:

	public function addAllData()
	{
  		$link = mysql_connect('localhost', 'root', 'root');
		if(!$link)
		{
			$message = "Could not connect!";
		}
		$link = mysql_select_db('test');
		if(!$link)
		{
			$message = "Could not connect to database!";
		}
   		$query = "SELECT `allcounts` FROM `sitecounter`";
		$result = mysql_query($query);
		$row = mysql_fetch_array($result);
		$counts = $row['allcounts'];
		$newcount = $counts + 1;
		$query = "UPDATE `sitecounter` SET `allcounts` = '$newcount'";
		$result = mysql_query($query);
		if(!$result)
		{
			$message = "Could not add data!";
		}
		else
		{
			$message = $row['allcounts'];
		}
		return $message;
	}

We first need to connect to the host and the database. Then we select the row from the table and define the row variable. The number of counts is held by the $counts variable. We add 1 to it and update the table. Then we return the updated number in form of the variable $message. The other function “addUniqueData()” is very similar. We need, however, a third function, which just returns the number of unique visitor counts without adding a new count. All the functions could have been condensed or shortened, however, for the purpose of simplicity I left it this way. The whole class script is shown here.

The MXML file

When we create the project in Flash builder we have of course a MXML file. As you could see from the movie, we have a pie chart within a panel. So this is what we create first. We just create an instance of the pie chart and give it an id of chart.

	<s:Panel title="Page counts (Flash builder 4)" 
	borderAlpha="0" backgroundColor="0xF9F5F1" 
			 width="450" height="450">
		<s:layout>
			<s:VerticalLayout paddingTop="20"/>
		</s:layout>
		<mx:PieChart id="chart"/>
	</s:Panel>

NOTE: Before adding a pie chart I used two Label components to develop this application to see all the messages.

When you test this movie all you will see is the panel but no pie. That is, because we have no data for the pie. We need to create a php file instead of the html file, which holds the movie. We need to set a cookie at the beginning of the page, for a change we use a php cookie to mark visitors who have opened the site.

<?php
if (isset($_COOKIE['user']))
{
	$myCookie = 'true';
}
else
{
	$myCookie = 'false';
}

$expire=time()+3600;
setcookie('user', 'FLSitecounter', $expire);

We ask if there is a cookie with the name user. Later we create a cookie with the name user and let it expire in 1 hour. If the cookie is valid the variable $myCookie will be “true”. We use a String here instead of a Boolean. Now we need to make another change and add flashvars. We add this line

flashvars.myCookie = '$myCookie';

after

var flashvars = {};

This allows us to retrieve the $myCookie value using flashvars. Now it is time to go back to the Flex movie script. When the movie opens we want two tasks accomplished, 1. check for unique visitors and 2. add every visit to have all the site visits recorded. So in th opening we add an initializer.

initialize="application1_initializeHandler(event)">

In this function we catch the flashvars value.

protected function application1_initializeHandler(event:FlexEvent):void
{
	myBoolean = this.parameters.myCookie as String;
	sendRequest('_unique')
}

And we create a function sendRequest with a String parameter to send a request to the server. In order to do that we need a RemoteObject component pointing to gateway.php, which is a connection to the Zend AMF service and pointing to the SitecounterService class of our php script in the services folder. We also create a CallResponder object, which makes it possible returning the call.

<fx:Declarations>
<s:RemoteObject id="dataService"  endpoint="gateway.php" 
	source="SitecounterService" destination="SitecounterService"/>
<s:CallResponder id="dataResponder" 
result="dataResponder_resultHandler(event)"/>

But first let’s have a look at the sendRequest function, where the call is sent out.

private function sendRequest(_dataRequest:String):void
{
	dataRequest = _dataRequest;
	if(dataRequest == '_unique')
	{
		if(myBoolean == "false")
		{
			dataResponder.token = dataService.addUniqueData();
		}
		else
		{
			dataResponder.token = dataService.getUniqueData();
		}
	}
	if(dataRequest == '_all')
	{
		dataResponder.token = dataService.addAllData();
	}
}

Depending on the dataRequest and the $myCookie value from flashvars we call the functions in the SitecounterService class. Then we wait for the response (result) from the server, which is handled in this listener function.

protected function dataResponder_resultHandler(event:ResultEvent):void
{
	myResult = event.result as String;
	if(dataRequest == '_unique')
	{
		unikCounts = int(myResult);
		sendRequest('_all');
	}

Here we store the value for unique counts in a variable unikCounts, which is bound. Then we send the next request to count all visits. When that respnse is coming back from the server we create the pie chart.

		if(dataRequest == '_all')
		{
			allMyCounts = int(myResult);
					
			var series:PieSeries = new PieSeries();
			series.field="number";
			series.labelField="descript";
			series.explodeRadius=.02;
			series.setStyle("labelPosition", "inside");

			chart.visible=true;
			chart.dataProvider=salesData;
			chart.width=440;
			chart.height=440;
			chart.series=[series];
			contentGroup.addElement(chart)
		}

However, we also need to create a data model to provide a DataProvider. We use the Model object and create an XML file as DataProvider where we store the variables with the counts. We convert the data to an ArrayCollection. The variables need to be bound variables.

<fx:Model id="numDistribution">
	<counts>
		<row>
			<descript>Unique counts: {unikCounts}</descript>
			<number>{unikCounts}</number>
		</row>
		<row>
			<descript>All counts: {allMyCounts}</descript>
			<number>{allMyCounts}</number>
		</row>
	</counts>
</fx:Model> 
<s:ArrayCollection id="salesData" source="{numDistribution.row}"/>

And this is basically all. Check here to see the complete script. When we test the movie we will see that all counts increase but unique counts only as long as the cookie is not placed. We now need to upload the files to the server. How that is done is described here.

Leave a Reply

You must be logged in to post a comment.