Friday, April 27, 2007

Mapping VO's from Flex to PHP using AMFPHP

I sometimes wonder why it is that I never seem to blog till shortly after the midnight hour... oh well... life just gets too crazy when the sun is up. So as it happens, one of my minions spent the better part of today putting together php classes, using a nifty code generator found called DAO Generator by the guys over at Titantic Linux. It seems to do a pretty decent job of generating the sql necessary to create the db table, and then builds three additional files, the VO, a datasource file, and then finally a DAO file that has a ton of functions in it. (and I mean a ton!)

Going to take a moment here to give credit where credit is due... Michael Ramirez's tutorial on Using Amfphp 1.9 with the Adobe Flex 2 SDK is what really got us started in the right direction, it's pretty detailed and yet easy to follow. We quickly were able to get our AMFPHP up and running with the tutorial files as outlined by Michael. Tickled pink by the code generator we figured we could easily start building our own php gateway. But enough background... on to the thick of things.

Passing VO's from PHP seems to be very well covered in numerous articles on the web, and it involves mainly adding a var $_explicitType="tutorials.Person" to the php VO, with a value that corresponds to the [RemoteClass(alias="tutorials.Person")] in the Flex VO. Pretty straightforward and foolproof. But no one seems to spend any time talking about going back the other way.

Generally when a VO is passed from Flex to AMFPHP, it is treated as an Associative Array. In Michael's examples, he treats the ValueObject that is passed back to Save function as just that $valueObject["lastName"]. But we were pretty keen on using the generated code, which actually uses the syntax $valueObject->getLastName(). And this of course, failed, because the $valueObject being passed to PHP from Flex was not in fact being mapped back to the right VO, or any php VO for that matter.

Turns out, after much googling, that only under certain conditions will AMFPHP successfully map an incoming Flex VO to the corresponding PHP VO. In the globals.php, found at the root of the AMFPHP folder structure, you'll find the following line:

$voPath = "services/vo/";

Meanwhile we had been placing our VO in the same folder as our Datasource and DAO files, something like com/crazedCoders/testapp, and this was off the services/ folder, not the services/vo folder. In fact we didn't even have a /vo folder. I found this little tidbit of information: "As for incoming class mapping, remember that if amfphp doesn't find the class to be mapped in the services/vo folder, it will simply deserialize the object as though it were untyped, that is, as an associative array. " in this blog.

It took a little bit of playing around but ultimately, without making any changes to the core AMFPHP files, I was able to get the reverse mapping working successfully. This is what that looked like:

//file: src/tutorials/Person.as
package tutorials{
[RemoteClass(alias="tutorials.Person")]
[Bindable]
public class Person {
public var firstName:String;
public var lastName:String;
public var phone:String;
public var email:String;
}}
and then in php:
<?php
//file: services/vo/tutorials/Person.php
class Person {
var $firstName;
var $lastName;
var $phone;
var $email;
// explicit actionscript package
var $_explicitType = "tutorials.Person";}
function formatLastName(){
$lastName = strtolower($lastName); }
?>
To test the mapping I added the following function to a PersonService.php file:
//file: services/tutorials/PersonService.php
function modify($person){
//this will call a function on person and return it
$person->formatLastName();
return $person;
}
Only if the valueobject was mapped correctly would it be able to call the function on the PHP VO. In Flex I just created a Person object, passed it in to the remoteobject call, and observed the formatting of the last name on the Person object that was returned.

Again, I hope this will save others the time that it took me to figure this out. Enjoy!

Wednesday, April 25, 2007

SizeableTitleWindow & Custom Skins

Most of you are probably familiar with the SizeableTitleWindow.as that the CF code generator for Flexbuilder spits out, along with a plethora of other useful tidbits of code. In fact that was the only reason I initially installed Coldfusion and the tools - I saw a modal resizable window in Flex and absolutely had to have it!

That was like 8 months ago. Recently I started working a lot more closely with skinning and runtime loading of css. I created some really funky UI's using run time style sheets that I found at http://www.scalenine.com, in particular I like using the Obsidian Theme Skin. However, this skin, like many others, replaces the skins for the Panel control - which, though very cool, breaks the resize function of the SizeableTitleWindow.

In simple terms, an event listener attached to the MouseOver event checks the coordinates of the mouse and if the coordinates fall within the right range, a cursor image is assigned. When the user clicks the mouse, the mouse down event checks which cursor is active and acts accordingly. The only problem is that all the coordinate calculations are based on event.localX and event.localY and those relate to event.target. However when using skins, the event.target isn't the SizeableTitleWindow but rather the skin, so it throws everything off. The result? The east and south cursors don't appear and even when they do, the drag functionality is buggy at best.

I fixed the problem by replacing all localX and localY with event.currentTarget.mouseX and event.currentTarget.mouseY. Also I no longer check to see if event.target is SizeableTitleWindow, and that seems to have fixed it.

You can find this code in action here and the source here. Enjoy.

Friday, April 20, 2007

Flex Modules, Compile and Run Time CSS

I've recently become involved in building a very module based Flex app, where the question of css and css inheritance came up, particularly with respect to how Flex handles run time loading of style sheets when they are loaded within not only the shell application but also the therein loaded modules.

Essentially, there are 3 rules that prevail:

  1. The most recent style to be loaded always wins.
  2. Run time overrides compile time styles
  3. StyleManager is a global Manager
  4. Style inheritance is granular to the attribute level
  5. Compile time css will only compile styles found in Application
Let me explain further, and to do so I'm just going to use our trusty <mx:Button>

The most recent style loaded always wins
Say you load a runtime style sheet with the following:

Button {
fillColors: #ff0000, #ff0000, #ffffff, #eeeeee; /*red */
letterSpacing:3;
}

Then in a (rather large) module you load another runtime style sheet with this:
Button {
fillColors: #006600, #009900, #ffffff, #eeeeee; /*green*/
letterSpacing:1;
}

You'll notice that the first color style is applied right away, to any buttons in the shell application. However, when the second module finishes loading, all Buttons will change from Green to Red, and spacing will be reduced to 1. To make it even more interesting, you could add an additional module of roughly the same size as the first and have it load its own style sheet. Then the end result is pretty much random, whichever module takes the longest to load wins, the shell run time style never to be heard from again.


Run time overrides compile time styles
In your shell application you add the following:
<style>
Button{
fillColors: #9900ff, #9900ff, #ffffff, #eeeeee;
letterSpacing:1;
}
</style>

Once your app loads the run time css, this will be overwritten. Now if you have a huge run time css swf with massive fonts or images embedded in, there's a chance you might even see your original color first and then have it overwritten later. This can cause for some funky effects in your app, in which case you might want to attach an eventListener to StyleEvent.COMPLETE, and hide your interface until that event has triggered using a ViewState or the like.

StyleManager is a global Manager
It that does not distinguish between <Applications> and <Modules>. Say you create a custom style class called .myDogAteMyHomeworkButton for Buttons in your module. You then place a corresponding style entry in your compile time or run time styles for this module. Now someone else happens, just happens to use the same exact style class in their module. Or the shell application developers happens to do so. Well again, the last one loaded wins. Your custom style class is never safe. But then again neither are their's. The best thing you can do is be very very unique in your style class naming conventions, and hope for the best.

Style inheritance is granular to the attribute level
Getting back to our original example, you'll notice the style attribute letterSpacing was defined explicitly in both style sheets. Because inheritance is on the attribute level, if you do not specify an attribute in say your run time style sheet for your application, then that attribute can be set in compile time style tags and it will override the default values. What's the lesson to be learned here? If you want to make sure that your runtime css has the final word, then get detailed and explicitly list every style attribute and its value, even if the default will suffice.

Compile time css will only compile styles found in Application
Ever seen this warning "The type selector 'HDividedBox' was not processed, because the type was not used in the application."? Until the dawn of Modules, this was a message I generally ignored. Made sense to me, if I didn't have an HDividedBox anywhere in my application, why include the style? But what would happen to modules that perhaps do use the HDividedBox control but rely solely on the shell application styles for their look and feel? The application doesn't know at runtime that one or more of its modules will need this style defined, so therefore it just ignores it. End result, your HDividedBox in your module will not be styled properly. The solution? Use run time stylesheets. (and that's how this all began!)

Tuesday, April 10, 2007

A closer Look at IFrames and ExternalInterface in Flex

Well I've been super busy as usual, working on some pretty cool stuff, still managing to only put food on the table but also sticking to my guns and doing only Flex projects. Of course, my blogging has suffered dearly.

In one of my current projects, I am faced with the challenge of somehow embedding IFrames inside my flex app, however without having any control over the html wrapper that my Flex app will sit in. Sure I could 'advise' users on adding the appropriate javascript functions and the hidden div element at the bottom of the body, as we've seen in other Flex Iframe examples out there. But I figured there had to be a way to do this without needing to rely on this external dependency.

As it turns out I can do inline Javascript function calls within my ExternalInterface.call, an example of this would be:

ExternalInterface.call("function(){return window.location.href;}");
which is a simple little function to quickly get the address of the current page. Another handy example is this one:

ExternalInterface.call("function(){document.location.href=document.location;}");
This is a quick way for a user to 'logout' of the flex application, it simply reloads the web page. So as you can see, we can do a great deal without ever needing to touch the html wrapper. So why not do the same thing with Iframe support? Here's what I came up with:
ExternalInterface.call("function(){" +
"var tempIFrame=document.createElement('div');" +
"tempIFrame.setAttribute('id','vyFrame');" +
"tempIFrame.style.position='absolute';" +
"document.body.appendChild(tempIFrame);" +
"tempIFrame.style.backgroundColor='transparent';" +
"tempIFrame.style.border=0;" +
"tempIFrame.style.visibility='hidden';}");
I am going to try and create a div element in memory and append it to the DOM. It's best to run this code during the application preinitialize() event. However, before I move on to explain the rest I just want to mention that I did run into some issues here with IE6. As you'll notice I appendChild and then I set the styles. Turns out that if I manipulate a new element too much prior to adding it to the DOM, it just gets all flaky and will not work. Believe me, this was not an easy bug to track down!

Now, we need to change the remaining externalInterface calls as well... things like move, hide, show and source. Building on the example at deitte.com that first got me started ages ago, I changed all the calls as they are found in his IFrame.mxml component:

ExternalInterface.call("moveIFrame",globalPt.x ,
globalPt.y, this.width, this.height);
Becomes:
ExternalInterface.call("function(){" +
"var frameRef=document.getElementById('vyFrame');" +
"frameRef.style.left=" + globalPt.x + ";"+
"frameRef.style.top=" + globalPt.y + ";" +
"var iFrameRef=document.getElementById('vyIFrame');" +
"iFrameRef.width=" + this.width + ";" +
"iFrameRef.height=" + this.height + ";}");
ExternalInterface.call("loadIFrame", source);
Becomes:
ExternalInterface.call("function(){vyFrame.innerHTML='" +
"<iframe id=\"vyIFrame\" src=\"" + source +
"\" frameborder=\"0\"></iframe>';}");
ExternalInterface.call("showIFrame");
Becomes:
ExternalInterface.call("function(){" +
"document.getElementById('vyFrame').style.visibility='visible';}");
ExternalInterface.call("hideIFrame");
Becomes:
ExternalInterface.call("function(){" +
"document.getElementById('vyFrame').style.visibility='hidden';}");

After a bit of testing I did manage to get this to work, sort of. I ended up spending some time playing with the compiler options in Flexbuilder. I found that if I turned off history management, my Iframes wouldn't appear. However removing the script reference to history.js seemed to have no real effect. For those of you that are not Flash-savvy :) it turned out that the only things to really watch out for, and again I am at the mercy of the users who embed my flex app into their html pages, is that the AC_FL_RunContent() has a final parameter setting of "wmode", "opaque" and the object embed tag also contains wmode="opaque". If this setting is not there or set incorrectly the Iframe will appear behind your flash player.