Flex and PHP

Flex and PHP builds highly-interactive, media-rich and Internet-connected applications that can run in every Web browser.

If you’re a PHP developer, you enjoy many benefits: PHP is object-oriented; PHP applications deploy easily; and the PHP community at-large produces a vast array of classes, libraries, and tools that ease and facilitate coding.

But PHP applications (as well as applications constructed in all other Web programming languages, including Perl, Python, and Java) decidedly lack interactivity. For example, even the simple task of completing a wizard-like Web interface, say, to purchase an item from an online store, requires many round-trips to the server. Fetching each form in the series requires a round-trip, as does each step of validation. And while Web surfers have come to expect such page refreshes and delays in Web applications, the end-result is the nonetheless unsatisfying: the user experience of the Web is typically inferior to what can be done on the desktop.

Or was inferior. Now many parts of the Web look, feel, and act like shrinkwrapped software. The sea change? A variety of techniques and technologies. But which is the right one?

In the past year or so, JavaScript and XML, the so-called “AJAX,” have improved the interactivity of Web applications. However, AJAX is not a panacea. Browsers remain inconsistent, translating to a herculean effort to validate an application. It’s common to find a morass of HTML and JavaScript exceptions for Internet Explorer 6, Internet Explorer 7, Firefox, and Safari, just to name a few of the divergent browsers.

AJAX security is also an issue. The article “JavaScript Hacking”, online at http://getahead.org/blog/joe/2007/03/05/json_is_not_as_safe_as_people_think_it_is.html is a well-known exploit found in Yahoo IO, Prototype, Dojo, and Mochikit, and more. Finally, while AJAX may animate dialogs, it’s difficult to mix rich media — video, animation, music, and sound effects — into the user interface.

Ideally, the features of a rich Web application would be apportioned to match the strengths of each service tier. Data retrieval and persistence would remain the purview of the database engine (for example, MySQL or SQL Server). Business logic would be implemented in PHP on a central server. PHP would process incoming user input and effectuate change in the database. PHP would also retrieve data and return new information to the user. That leaves the third tier — the client — to interact with the user. More specifically, and in the context of a Web application, “the client” is likely the browser.

But if the browsers are notoriously mercurial, and it’s cost-prohibitive to provide custom software on every combination of operating system and processor, how can the ideal be realized? How can a single application look and feel great, and run on every platform?

The answer? Flash — and an entirely new tool set named Adobe Flex. Flex is a set of tools and technologies that you combine to construct, deliver, and run rich, sophisticated, and snappy Web applications. Flex can add a sexy widget in a larger page, or can entirely replace your PHP application’s user interface. Flex runs in Flash Player — found in nearly every Web browser on the planet. (Flash Player 9 or higher is required to run Flex applications.)

Even better, many Flex components are about to be released as open source according to the terms of the Mozilla Public License (MPL).

Building a Better (and Simpler) Web Application

Figures One and Two summarize the distribution of responsibilities in a traditional PHP Web application and in a Flex application, respectively.

FIGURE ONE: The traditional PHP programming model

Figure One (ignoring the addition of AJAX) depicts the classic behavior of PHP applications. Initiated by user action, the browser connects to a Web server running PHP and requests a page. Business logic in the PHP code responds to the request, a process that may require validation of incoming data, data retrieval from the persistent store, computation, and the rendering of a result in HTML, perhaps customized to the user’s browser, since browsers are irregular. Both the client and server are stateless, which requires both to regenerate the state of the application every time.

FIGURE ONE: The Flex and PHP programming model

Contrast Figure One with Figure Two, which depicts the Flex model. In Figure Two, the role of the Web server is greatly simplified, limited to data manipulation (read/write) and computation. The server’s output is neutral XML. On the client, the browser runs the Flash application in an isolated Flash Player environment. The Flex application — which could be a single element in a larger, traditional Web page or a complete Web site — renders the user interface, reacts to mouse clicks and other input events, and changes from one interface “screen” to another (the various states of a user interface are called view states in the parlance of Flex). The Flex application is stateful, unburdening the server from rework. The style, content, and visuals of the application are essentially boundless, limited to the capabilities of the Flash Player. And the application runs consistently on any platform that Flash Player has been ported to, including Linux, Mac OS X, and Windows.

Introducing Flex

Flex is a set of tools and technologies that you combine to construct, deliver, and run rich, sophisticated, and snappy Web applications. Flex can add a sexy widget in a larger page, or can entirely replace your PHP application’s user interface.

All Flex applications are deployed via Flash Player, and leverage familiar and mature standards, including XML, web services, and HTTP. XML describes data and is used to relay between the application and the server (s) web services provide the infrastructure; you can also use HTTP directly to connect to URLs.

Flex includes all of the software required to build an application:

*The Flex Framework is a large collection of classes used to build rich Internet applications. The Flex Framework, like other user interface class libraries, provides forms, menus, media players, buttons, and smart layout containers. Further, the Flex Framework furnishes controls usually found in desktop applications, including a rich text editor, a color picker, and a date chooser. You can also change the cursor, apply visual effects and animations, and enable drag-and-drop in your software.

Additionally, the Flex Framework provides components to execute remote procedure calls, and format and validate data. Moreover, the Flex Framework manages the state of your user interface. At a macro scale, a view state can be a pane in a wizard-like form. At a micro scale, a state can reflect the current visual appearance of a control, such as unavailable or “checked”. You can traverse the history of state changes, allowing navigation through a series of ordering screens.

While many AJAX toolkits provide a pool of similar controls, those found in the Flex Framework are written in ActionScript, a true object-oriented programming (OOP) language, and work flawlessly in all browsers on all platforms.

The Flex Framework is part of the free — and open source — Flex SDK. The SDK includes the Flex class library and a suite of command-line tools to build and debug Flex applications. You can download the Flex SDK from http://www.adobe.com/products/flex/sdk. You can read about Adobe’s plans to open source Flex at http://www.flex.org.

*Flex Builder is a robust integrated development environment (IDE) for Flex applications. Flex Builder is based on Eclipse, and you can choose to install either the plug-in version of Flex Builder or the standalone version of the tool. (The former assumes you already have a working Eclipse setup; the latter installs everything you need to run Flex Builder and has no prerequisites.) Using Flex Builder, you can interactively build user interfaces, debug your code, and build applications from scratch. Figure Three shows Flex Builder in action.

FIGURE THREE: Figure 3: The Adobe Flex Builder application, shown edting the user interface of an online store application

While the Flex SDK is free, the Flex Builder integrated development environment is not. You can find more information about Flex Builder at http://www.adobe.com/go/flexbuilder.

*MXML is an XML-based markup language used to describe screen layout, and is an essential part of Flex. MXML specifies how to assemble a user interface from controls, and can also describe how the user interface should behave, including view states, transitions, data models, and more. For example, the MXML snippet in Listing One produces the top two left-most panels in the interface shown in Figure Four.

LISTING ONE: A sample of MXML code

<mx:Canvas left=”10″ top=”10″ width=”100%” height=”60″
backgroundColor=”#ebebe9″ styleName=”homeSection”>
<mx:Label left=”10″ top=”10″ text=”Search Product” width=”112″ height=”22″
<mx:Button left=”168″ top=”30″ label=”Go” width=”47″ height=”20″ styleName=”glass”
click=”Alert.show(’This feature is not implemented in this sample’, ’Go’)”/>
<mx:TextInput left=”10″ top=”30″ height=”20″ width=”150″/>

<mx:Canvas left=”10″ top=”78″ width=”100%” height=”280″ backgroundColor=”#ffffff”
<mx:VBox left=”10″ top=”10″ width=”100%” height=”100%” verticalGap=”0″>
<mx:Label text=”Programs for Your Lifestyles” styleName=”sectionHeader”/>
<mx:HRule height=”5″ width=”197″/>
<mx:Label text=”Active” styleName=”homeProgramHeader”/>
<mx:Label text=”Product Warranty” fontSize=”9″/>
<mx:Spacer height=”8″ width=”100%”/>
<mx:Label text=”Business” styleName=”homeProgramHeader”/>
<mx:Label text=”Upgrades, Data” fontSize=”9″/>
<mx:Label text=”Traveler” styleName=”homeProgramHeader”/>
<mx:Label text=”International Roaming” fontSize=”9″/>
<mx:Label text=”Students” styleName=”homeProgramHeader”/>
<mx:Label text=”Music Downloads” fontSize=”9″/>
<mx:Label text=”Kids” styleName=”homeProgramHeader”/>
<mx:Label text=”Games, Ringtones” fontSize=”9″/>

Here, MXML organizes labels and other widgets into larger canvases. Much like HTML, attributes dictate sizes, colors, offsets, font metrics, and labels. This MXML file is compiled into ActionScript, and is then fused with the application’s assets, code and graphics, into a single Flex application. SWF file.

FIGURE FOUR: A portion of this interface was created using the snippet MXML code found in Listing One

Ultimately, all Flex software is translated to ActionScript, the native language of the Flash Player. Learning ActionScript should be a priority because most applications require procedures, custom classes, or other glue that can only be achieved in ActionScript. You can also change the cursor, apply visual effects and animations, and enable drag-and-drop in your software via ActionScript.

Figure Five pictures all of the assets that can be combined into a Flex application.

FIGURE FIVE: The construction of a Flex application

Mixing Flex and PHP

With Flex assuming the chores of user interaction within the client, PHP code can be simplified to focus solely on business logic.

As an example, consider a department store shopping application. Assuming the shopping client provides navigation among categories (sporting goods, jewelry, electronics), item selection within a category (shirt sizes, styles, and colors), and checkout (personal information, credit card information, shipping options), PHP could:

*Generate a list of available categories.

*Scan inventory for available items and create an XML-based manifest for the application to subsequently display.

*Retrieve customer information, such as preferences, previous purchases, new product recommendations, and personal information.

*Process final checkout, including billing, generating pick requests to fulfill the order, adjusting inventory levels, and assigning package tracking information to the order. If the client waits for confirmation, the outcome of the transaction (success, failure, exception) can be returned to the client via XML.

Flex can retrieve information from the Web via simple HTTP requests or via SOAP requests. (A third method, Flash Remoting, a kind of remote procedure call, is also available, and is more efficient. To use Flash Remoting, install Flex server software or one of a number of open source solutions, such as Amfphp (http://www.amfphp.org/), WebORB for PHP (http://www.themidnightcoders.com/weborb/php) from the Midnight Coders, and SabreAMF (http://www.osflash.org/sabreamf).

Flex applications can issue simple HTTP requests for text or XML files. If the requested file is static, the request may be handled directly by the Web server. If the file is generated dynamically, the Web server may invoke PHP to generate the reply, usually returned as raw text or XML.

SOAP requests may be appropriate if you already have an established Web service infrastructure or would like to institute such a suite of modular services. You may also choose SOAP if you plan to consume third-party Web services.

Both approaches to intercommunication are valid, and which you choose depends on your requirements and preconditions. What’s most important is your recognition that Flex applications are more akin to client/server applications than Web applications. Thinking in “pages” becomes thinking in “transactions”.

Migrating to Flex

If you’re about to create an entirely new application, dividing your software into distinct client and server fiefs can be planned from the very start. However, chances are you have a PHP code base already producing results (and revenue). In this very likely case, let Flex enhance what you’ve deployed, making your best even better.

Your Flex applications need not be large or complex. For example, if you maintain a management “dashboard” to monitor sales or web traffic, say, you can embed a rich, Flex pie chart control into a Web page. Or you can create a user registration wizard, including local (client-side) field and form validation. Thinking larger, you could also replace your shopping cart viewer, or provide a drag-and-drop target for file uploads.

Adopting Flex need not be “all or nothing.” Implement, increment, and innovate.

To learn Flex rapidly, read the new book Programming Flex 2 from O’Reilly Media. The authors, both subject matter experts, provide the expertise required to build effective and interactive Flex applications from scratch.

Flex Your PHP Muscle

Flex and PHP is a powerful combination. Flex provides a large framework for user interface and rich client development. Better yet, a Flex application running within the ubiquitous Flash Player works across all platforms and all browsers. PHP, a language you’ve already mastered, is well-suited to business logic and database access. Stripped of laborious page rendering drudgery, coding is greatly simplified. Flex and PHP truly deliver rich Internet applications.

Fatal error: Call to undefined function aa_author_bios() in /opt/apache/dms/b2b/linux-mag.com/site/www/htdocs/wp-content/themes/linuxmag/single.php on line 62