Flex and PHP Architecture

Client/server architecture

If you want to categorize Flex applications, you can say that Flex applications follow SOA architecture model, where Flex is used to create the client and you connect the client to data using services.

Let’s go back to browsers and how web applications are delivered. When the browser makes a request, the server uses a combination of static content (HTML/CSS/JS code) and scripts (these scripts may query a database or call other scripts, but in the end they output HTML/CSS/JS) to prepare a page. This page gets loaded and rendered by the browser. A key element here is that, usually this page (or response) has the presentation markup and the data baked into the same message.

When a new state of the application is to be presented, the browser makes a new request and the server prepares the page. The client “just” renders the data.

Flex applications works differently. The server sends the compiled Flex application (the SWF file) that runs inside the browser using the Flash Player plug-in. Usually, this SWF file holds only the client-side business logic. If data are need (from a database for example) the Flex application makes a request for those data. The server sends only the data (this can be in XML, JSON, AMF3 format), and the client knows how to represent this data visually. What we have here is a service oriented architecture: The Flex application is the client―a client that can consume data services from the server. The application can change state without refreshing the page or reloading the SWF file in the browser. The application is a client that can do more than “just” render data. Thus using Flex and Flash Player it is possible to create almost anything that makes sense to deploy on the web, from games to applications, to widgets that are integrated within “classic” web applications, and more (see Figure 1).

Flex and PHP architecture

Figure 1. Flex and PHP architecture

Connecting Flex clients to PHP back-ends

As a PHP developer, you have a very direct way to read data, parse them, and display them on the screen. Connecting to a MySQL database is one of the first things any PHP developer learns.

What about Flex? I have to disappoint you, because you don’t have direct access to data stored in a database. Why is there no direct way of reading data from a database? Because of the old saying “You should never trust the client!” Suppose the client is a Flex component that knows how to connect to the MySQL server. How do you store the credentials so that it wouldn’t be easy to steal them and have the database compromised? Set a different user/password for each user and give them this information? This is just one of the reasons why it is not a good idea to have a client technology that can connect directly to a database server, without using an application server in the middle.

Basically, in Flex applications you rely on server-side scripts to manage the databases. Flex offers you a way to call the server pages and get back the answer in Flex. Basically, you can connect a Flex client to a PHP back-end in two ways: over HTTP or using sockets.

Over HTTP, there are four different ways to connect to a server data source: REST style services, web services (WSDL/SOAP), remoting (or RPC), and XML-RPC (see Figure 2).

Flex – PHP HTTP based communication

Figure 2. Flex – PHP HTTP based communication

You can use the HTTPService class to use REST style services. You can send POST variables when you do a request, and the response can be XML, JSON (there is a third-party library for parsing JSON), or custom formatting.

If you have web services on the server (SOAP/WSDL), you can use the WebService class.

But the most interesting method is remoting (using the RemoteObject class). There are three reasons why I think it is the coolest method. First, using remoting you can leverage any PHP class you have on your server by calling any public method. Basically, from the Flex side you use an instance of RemoteObject as if it were the remote PHP class. Second, you can map the data model from the PHP side to an ActionScript data model, and have the conversion done automatically. This is extremely important, because when you use typed objects, you get the benefits of compile-time error checks and code completion. This means code that is easier to read and less prone to bugs. And third, the messaging format for this method, AMF3 (Action Message Format) is a binary format, which can be much faster and smaller compared to SOAP/XML/JSON, especially for big sets of data. The format itself is open, and anyone can read the white papers and implement programs that use it.

AMF3 is faster because it encodes data. For example, if the same string is repeated in a data set, it is encoded one time, and all other occurrences of the string are references. If a number is smaller than four bits, only the minimum number of bytes required are used (see Figure 3).

Remoting or RPC

Figure 3. Remoting or RPC

Remoting is natively supported by Flex, however on the server side the story is not the same. PHP doesn’t support remoting and AMF3 natively. This is why you need a server side library to enable remoting for a PHP web server. There are four available libraries, all are free, and I wrote tutorials about how to use each of them: Zend AMF, AMFPHP, WebORB for PHP, and SabreAMF. And here you can read a post that compares them.

The last method used by people for integrating Flex with PHP is the light-weight web services XML-RPC. This is for example what Drupal offers out-of-the-box if you want to create modules that uses Flex or AJAX. In order to use XML-RPC you need a library for both the client (xmlrpcflash) and the server (phpxmlrpc).

If you want to connect using your own protocol built on top of sockets, you can use sockets communication. You can create a socket server on the PHP side, and from the client you can connect to this server and exchange data. Just a reminder―when creating Flex applications that target the desktop (running on Adobe AIR and not in the browser) you can create socket servers on the client side too. Here is a good article about working with sockets with Flex and PHP.

Asynchronous nature of Flex

The asynchronous nature of Flex is something rather different from anything in PHP. It is important to understand this, stop fighting it, and go with the flow.

What does it mean that Flex is asynchronous? Suppose you create a Flex application, and after the application is loaded in the browser, the user can choose to load pictures from another site. You might use a URLLoader class for this task. When you execute the load() method, on the next line of code you won’t have the data. The script doesn’t pause after the load() call waiting for the data to be loaded. Instead the execution of the script is resumed. As a programmer you deal with this asynchronous nature using the built-in AS3 events system. If you’re familiar with AJAX programming, this is similar to what you do when you make an AJAX call: you provide a callback function, and when the data arrives the callback function is called and you can access the loaded data.

Suppose you have a Flex application that loads a picture from a web server. In order to deal with the asynchronousity, you would add an event listener for the result event. This is the function that will be called once the data is loaded. Here is an example of how the code might look:

function loadPic():void {
var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.BINARY;
//adding the event handlers or listeners
loader.addEventListener(EventComplete, picLoaded);
loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, picError);
//starting the loading
loader.load(new URLRequest("http://some_url"));
//event handler for the result event
function picLoaded(event:Event):void {
//get the data from the loader object
//use the target property to get the loader object
(event.target as URLLoader).data;
//event handler for the error event
function picError(event:IOErrorEvent):void {
//displays the error id in a pop-up windonw

I can summarize it like this: Don’t call us, we’ll call you!

As I said, AS3 has a built-in event system. The top class of all events is Event. All objects that work asynchronously have an addEventListner() method, and the first two arguments are the event type and the name of the function to be called when the event occurs. You might think that only objects that deal with retrieving remote data are subject to this event model. Actually that is not the case; all components or objects that are visual also have events. For example, every Flex application has a creationComplete event. This event is triggered once all the required components from the application are processed and drawn on the screen.

Although you might feel that such code is not as straightforward as PHP, there is a good reason for having asynchronous calls scattered around in Flex (and Flash Player): Flex is a client-side technology. If all calls were synchronous, the user interface of the application would stop being responsive for any call that involved loading data, for example. And users hate unresponsive user interfaces.

You can cancel some events and even change the default behavior. I’ll let you explore these details on your own if you need to; for now you should have a fairly good idea of what events and event listeners are all about.


First of all let me tell you that you can communicate from Flex over HTPP or HTTPS. It depends on your need.

Second, when it comes to user authentication you can use basically the same workflow you use in HTML/PHP apps. For example suppose you authenticate the user from the client (could be an HTML form or could be a form from the Flex application itself). Back on the server, you validate the credentials and if correct you set some flags in session. All the calls you make from the Flex client to PHP scripts (using REST services, web services, remoting or XML-RPC) will append the session id to the request, and as a result the PHP will be executed with the same session information. And based on the session information you can check if the user has the rights to do what the operation is trying to do.

When it comes to code execution loaded after the application was initialized (for example your Flex application loads some widgets from other servers), Flash Player offer sandboxes as a way to ensure that foreign code (and potentially dangerous from the point of view of the security) is not accessing the variables from the main Flex application. This is done by default. For example if you have a Flex application that loads a weather widget from another domain, you don’t want the weather widget code to find what is the user name or his bank account is (suppose that the info is part of the Flex app).

If you trust the code you loaded (although this is a security risk) you can “import” instead of loading, and the widget code from the above example could execute in the same application domain as the Flex application code.

If you keep the loaded code in a separate domain (you don’t “import” the code), you can communicate from one domain to another using Local Connection. You can read more about these here. HP created a free application called SWFScan that scans Flash applications for a number of vulnerabilities. This is a good way to ensure that you don’t make mistakes.

Debugging Flex and PHP applications

The key element to keep in mind is: now, you have a client that is separated from the server, and problems may be on the client, on the server, or at the network level.

You can debug Flex code using the debugger from the Flex SDK, or the debugger from Flash Builder 4. If you choose a combined setup of Flash Builder 4 and Zend Studio, you can debug the PHP and Flex code from the same project very easily. Here is a tutorial on Zend Studio and Flex Builder debugging.

We added two new views to Flash Builder 4 that help you to debug the code: Network Monitor and Test Operation views. If don’t see these views you can add them from Window > Other Views… and look up at the views of the Flash Builder node (Network Monitor is available only in Flash Builder Premium).

Using Network Monitor view you can see all the communication that goes between the Flex client and the server. You can see both the raw data and the objects. If you want to use it, the first thing you have to do is to enable this feature: click on the Enable Monitor icon (see Figure 4).

Enabling Network Monitor

Figure 4. Enabling Network Monitor

After this, just run the application (you don’t have to do it in debug mode). As you use the application and data are exchanged with the server, you should see the requests, how long it took and data were send/received (see Figure 5).

Using Network Monitor

Figure 5. Using Network Monitor

Test Operation view, as the name implies, let’s you to test the available operations. Select Test Operation view and choose getData() operation and click Test. You should see the four VOAuthor objects (see Figure 6). If the operation expects arguments, then this view lets you define the arguments values.

Using Test Operation view

Figure 6. Using Test Operation view

Where to go next

If you want to learn more about Flex and how you can integrate Flex apps with PHP back-ends, you can have a look at my blog (in addition to a lot of tutorials, there is an introduction to Flex for PHP developers). Another great resource is Adobe Developer Connection where you can find a section dedicated to Flex and PHP. If you learn better by listening, Adobe TV has a lot of videos or screencasts.

What is flex ? basic Flex tutorial

What is Flex?

Enough digressions! Let’s start from the beginning: what is actually Flex (I assume by now everyone knows what PHP is)?

The simplest answer is: Flex is just another way of creating an application authored in Adobe Flash Professional on Adobe Flash Player. A Flex application gets compiled into a SWF file, which is played inside of the browser by Flash Player. Why did we need another way of creating applications authored in Adobe Flash Professional on Adobe Flash Player? Traditionally those applications were created using the Flash Professional authoring tool. If you take a look at this tool, you’ll notice that it is oriented primarily for designers. There is a stage, a timeline, drawing tools, and so on.

When you are developing applications and you care about productivity, you want components, you want to be able to streamline development as much as possible by reusing code, and not last but not least, you want a modern IDE.

Thus a revised answer could be: Flex is an open source framework that helps developers to quickly create Rich Internet Applications (RIAs) that run inside Flash Player or Adobe AIR (see Figure 1 for a list of built-in UI components). The framework was shaped pretty much as it is today with the arrival of Flex 2, Flash Player 9, and ActionScript 3. The current version is Flex 4.

Built-in UI Flex components

Figure 1. Built-in UI Flex components

Why Flex?

So using Flex you can create applications for Flash Player (web apps) or Adobe AIR (desktop apps). But what is so cool about building applications for Flash Player or Adobe AIR?

Well, at least there are two reasons: RIA and Contextual Applications.

If you compare the web applications with the desktop ones you can draw these points:

  • Web applications are cool because you can use them wherever you have a browser and an Internet connection. They have lower costs for distribution and maintenance because all you have to do is to update the server with the new version and all the clients are updated.
  • Desktop applications are cool because they offer great UI experience and at the same time are very responsive to the user actions.

Each of these two categories has its own strengths. Wouldn’t be cool to have a third category that combines the reachness and availability of web apps with the richness and responsivness of desktop apps? Actually this category already exists (since 2002 when Macromedia used for the first time this term) and it’s called Rich Internet Applications. With Flex you can build RIAs easily.

From its inception in 2002, RIA came a long way. The first use cases were public facing applications. In the last couple of years we’ve seen an increasing usage of RIAs behind the firewall, in the enterprise world. Using the RIA approach in enterprise means bigger ROI. In Figure 2 and Figure 3 you can see how a simple form for gathering data about car crashes can be implemented using RIAs. Instead of having a bunch of text areas that force the user to type in a lot of information, you can create a user interface that lets the user pick up the car, describe the damages, and “draw” the accident scene.

The RIA approach

Figure 2. The RIA approach

The RIA approach

Figure 3. The RIA approach

One may think that if you build your application with Flex you’ll have problems with users not being able to consume your application because they don’t have Flash Player installed. This is not true, because for years 98% of all connected computers have Flash Player installed.

And the beauty of it is this: as a Flex developer you don’t have to care about browsers with different implementations of JavaScript and CSS or about differences between the same browser on different operating systems. By targeting Flash Player you leverage its consistency across OSs and browsers.

What about Contextual Applications? Contextual applications “are characterized by their ability to adapt presentation and performance to different application contexts, including multiple operating systems, platforms, and devices; diverse and changing types of networks; and unique user expectations and personalization“.

A good example of the contextual applications is Times Reader by The New York Times (See Figures 4 and 5). This is an Adobe AIR application created with Flex, and it can run on desktops, laptops, PCs, tablets, and phones. It has offline support (you can read the news while not connected, because it saves these locally). It has the ability to adapt the content to the screen size (it can increase or decrease the number of columns, and remove pictures and articles from the active screen in order to fit the current size of the screen).

Times Reader running on HP’s slate tablet

Figure 4. Times Reader running on HP’s slate tablet

Times Reader running on my laptop

Figure 5. Times Reader running on my laptop

And finally I want to add to the case I’m building the Mobile world. More and more people have smartphones and use these devices for activities that not so long ago were possible only with laptop or desktop connected to a wire. And this trend is going in only one direction: UP! Soon there will be more people accessing the Internet from mobile devices than from computers. What about building applications for these devices? Well, to put it mildly is a nightmare. And it really isn’t someone’s fault! Having many companies building so many devices it is only natural to have specific ways for each platform (Symbian, Web OS, BlackBerry, Android, Windows Mobile, and iPhone).

2010 is the year when Adobe releases Flash Player 10.1 and Adobe AIR 2 for mobile devices (the first to receive this will be Android and BlackBerry; for iPhone you can use the next version of Flash Professional to package Flash apps as a native app). We are still working to create a Flex framework suited for mobile devices. Once you have this, you will be able to leverage your current Flex experience on mobile world.

Flex and AJAX

Both Flex and AJAX are client-side technologies and both can be used to create RIAs or to “augment” existent web applications. Like in the case of Flex, typically an AJAX application makes a request to server after the initial response was rendered, and injects the response into the existing page once the servers sent the answer to that call.

While Flex is an application framework to build apps for Flash Player or Adobe AIR, AJAX is a term that refers to a collection of technologies and techniques that include JavaScript, HTML, and CSS. Typically when you work with AJAX you use a framework (Ext JS, Dojo, jQuery, Prototype and so on). The reason you are doing this is mainly to cope with the differences between browsers implementations for JavaScript/HTML/CSS.

Having said that, in the end it is really up to you what technology to choose. If you prefer to work with a dynamic, weak-type, prototype-based language, you will probably favor AJAX. If you have experience with JavaScript and you don’t want to learn a new language, again AJAX is the answer for you. If you prefer strong-type, OOP languages, modern IDEs features you’d probably prefer Flex. Arguably Flex (and Flash Player) offers more flexibility and features when compared to what is possible with AJAX (even with the new additions of HTML 5). But again, there is no such thing as one is better than the other. It really depends on the nature of the project you are working on, your experience, etc.

In fact, there are people using both technologies to do things that would be impossible to do with only one of them.

Flex and PHP waltz

Flex is a client side technology; PHP is a server side technology. Both technologies are quite mature: you can find tools, frameworks and libraries, and articles/examples for any task or application type you might think of.

Both technologies are open, and both have the lowest entry point: your time to understand them. Using Flex or Adobe AIR SDK and PHP with vi doesn’t cost a thing, and the same is using the runtimes (Flash Player or Adobe AIR) and using a web server with PHP.

If you are used to code using IDEs you can buy Flash Builder and Zend Studio to create a powerful setup for Flex and PHP projects (both these IDEs are Eclipse based and can be installed together on the same Eclipse instance).

Finally it is about being able to create better applications, being able to use text, video, sound, animations, gestures, multi-touch to create rich user interfaces, being able to create real-time, collaborative applications, being able to use the same technologies and workflows across OSs and devices (computers, smartphones, tablets)…and having fun while doing this.

Summary :

Thus, in 2002, Macromedia came up with the term RIA (Rich Internet Applications) to describe a new breed of applications that combine the benefits of the web applications with the advantages of the desktop applications. The technology that made this possible was Flash Player.

Other Related Technologies:

today we see Silverlight from Microsoft and JavaFX from Sun.