AMFPHP Complex Classes – Yeah I knew that

Just blew half an hour tracking down something I *knew* I’d done before. Thought I’d post here for future ‘lapses.’

To return a typed object from PHP to the flashplayer the process is simple, declare a variable called $_expicitType in your PHP class
e.g.
class SummaryVO
{
var $_explicitType = "com.dl.SummaryVO";
$standards = array();
$levels = array()
}

In your corresponding ActionScript class use the RemoteClass metadata tag

package com.dl
{
[RemoteClass(alias="com.dl.SummaryVO")]
public class SummaryVO
{
public var standards:Array;
public var levels:Array;
}
}

Note the values for $_explicitType and alias are arbitrary, they can be what ever you’d like, as long as their the same in AS and PHP (provided your only conerned with PHP=>AS mapping).

Okay, so what happens when you have ‘complex classes’ you’d like to return? Complex meaning a class who’s members are made up of other ‘custom’ class instances.

Let’s say, for example, that in our later code example ‘standards’ was an array of ‘StandardVO.’ The problem I ran into was that I was getting a typed ‘SummaryVO’ back from AMFPHP, however my class members were not typed, just generic objects. I checked and I had taken the necessary steps to use strongly typed SummaryVO and StandardVO classes, yet the StandardVO was coming back as a plain old Object.

We’ll it turned out in my development flurry I hadn’t used a reference to the ‘StandardVO’ class yet!! Simply declaring an instance of StandardVO did the trick (i.e. var placeHolder:StandardVO). You could also you the includes class […] compiler option.

Moral of the story, be sure the complier includes a reference to any class you want strongly typed from your RPCs.

Pipe Demo: Mortgage App

I’ve posted a pipes version of the mortgage app.

Things to note:

You can load / unload the modules dynamically.

A junction mediator is defined for each ‘player.’ In the mortgage app context that’s a mediator for the application itself, the Acme widget and the Foo widget.

ApplicationJunctionMediator
ModuleJunctionMediator (Acme)
ModuleJunctionMediator (Foo)

To make our lives easier when it comes time to unload the module, the module caches the app’s pipe fitting it’s connected to. This allows the module to easily ‘cleanup’ (disconnect our fittings) should we want to unload the module. You may find a cleaner approach to this, feel free to post in comments – the ‘caching approach’ was simple and thus the road taken for the demo.

Understanding PureMVC Pipes

Disclaimer: This a bit of a longer post!!

The pipes utility is newer to PureMVC and as such, I’ve seen questions on the blogosphere regarding it’s use.

The plumbing metaphor should help wrap you head around this utility and it’s use. Keep in mind that a pipe allows for one-way message flow.

So let’s take a look at how the utility can be used.

One great features of ‘Pipes’ is that they can use used on top of an existing app. That is, you’ll simply need to define a JunctionMediator at/for each integration point.

Let’s look at the simplest case, an application that loads and communicates with a module. We’ll assume that at some point you’ll want to use this same app to use multiple modules down the road. You’ll need to create a JunctionMediator for the application and a JunctionMediator for the module. We’ll dive into the details for those mediators but at a high level, that’s it – we simply define a ‘JunctionMediator’ for each ‘player.’

Here’s a simple diagram

Simple Pipe

Our JunctionMediator’s will be connected together with pipes. We’ll have one pipe that allows for application-to-module message flows and another pipe that allows for module-to-application flows.

On the receiving end of a pipe, we’ll want a pipe listener (you’ll have only one pipe listener for a given pipe). We’ll use pipe listeners to handle incoming pipe messages.

To send messages down a pipeline, we’ll normally use the Junction’s ‘sendMessage’ function.

Back to our simple example, our app’s JunctionMediator would be responsible for creating the app’s pipe fittings, creating pipes to connect to those fittings to the module.

So the first thing our app’s JunctionMediator would do would be to create a new junction at creation.


public class ApplicationJunctionMediator extends JunctionMediator
{
public function ApplicationJunctionMediator()
{
super(NAME, new Junction());
}

Once this mediator is registered with our facade, we’d want to create the PipeFittings. We’ll use a TeeSplit for outgoing and TeeMerge for incoming. The TeeSplit will allow us to connect to multiple modules for outbound messages. The TeeMerge will allow multiple modules to send messages up to our main app. We’ll also want to add a pipe listener on our TeeMerge. This listener will allow us to handle the messages being sent up from the modules to the app.


override public function onRegister():void
{
junction.registerPipe( PipeAwareModule.APP_TO_MODULE_PIPE, Junction.OUTPUT, new TeeSplit() );
junction.registerPipe( PipeAwareModule.MODULE_TO_APP_PIPE, Junction.INPUT, new TeeMerge() );
junction.addPipeListener( PipeAwareModule.MODULE_TO_APP_PIPE, this, handlePipeMessage );
}

Our handlePipeMessage function is responsible for handling the messages coming up from our modules to our app.


function handlePipeMessage(message:IPipeMessage):void

Being a Mediator, we can define what application-level notifications we’re interested in and how to handle those notifications. That is, we’ll want to utilize listNotificationInterests() and handleNotification(note:INotification). We’ll use these to listen for notifications and turn desired notifications into messages to pass down our pipes.

For example, our Mortgage App would listens for request for loan notifications and turn those notifications into messages.


override public function handleNotification(note:INotification):void
{

switch( note.getName() )
{
case MortgageAppEventNames.REQUEST_FOR_LOAN:
var loanMessage:Message = new Message(MortgageAppEventNames.REQUEST_FOR_LOAN,null,note);
junction.sendMessage(PipeAwareModule.APP_TO_MODULE_PIPE,loanMessage);
break;
}
}

Our application JunctionMediator will also typically listen for a notification that a module has been loaded. Our app’s JunctionMediator will then create new pipes to connect the app’s junctionMediator to the modules junctionMediator. Something along the lines of…


override public function handleNotification(note:INotification):void
{

switch( note.getName() )
{
case MortgageAppEventNames.REQUEST_FOR_LOAN:
var loanMessage:Message = new Message(MortgageAppEventNames.REQUEST_FOR_LOAN,null,note);
junction.sendMessage(PipeAwareModule.APP_TO_MODULE_PIPE,loanMessage);
break;

case ModuleEvents.CONNECT_MODULE_JUNCTION:
var module:IPipeAwareModule = note.getBody() as IPipeAwareModule;

// Create the pipe
var moduleToApp:Pipe = new Pipe();
// Connect the pipe to our module
module.acceptOutputPipe(PipeAwareModule.MODULE_TO_APP_PIPE, moduleToApp);

// Connect the pipe to our app
var appIn:TeeMerge = junction.retrievePipe(PipeAwareModule.MODULE_TO_APP_PIPE) as TeeMerge;
appIn.connectInput(moduleToApp);

// Create the pipe
var appToModule:Pipe = new Pipe();
// Connect the pip to our module
module.acceptInputPipe(PipeAwareModule.APP_TO_MODULE_PIPE,appToModule);

// Connect the pipe to our app
var appOut:TeeSplit = junction.retrievePipe(PipeAwareModule.APP_TO_MODULE_PIPE) as TeeSplit;
appOut.connect(appToModule);

break;

// And let super handle the rest (ACCEPT_OUTPUT_PIPE, ACCEPT_INPUT_PIPE, SEND_TO_LOG)
default:
super.handleNotification(note);

}
}

Finally our application’s JunctionMediator will handle the incoming pipe messages.


override public function handlePipeMessage(message:IPipeMessage):void
{
// Handle our Module->Application integration
trace(message);
var note:INotification = message.getBody() as INotification;

switch(note.getName())
{
case MortgageAppEventNames.LOAN_QUOTE_READY:
sendNotification(note.getName(),note.getBody(),note.getType());
break;
default:
sendNotification(note.getName(),note.getBody(),note.getType());
break;
}
}

That covers the basic responsibilities for our app’s JunctionMediator.

Our module’s JunctionMediator would listen for messages coming in on the APP_TO_MODULE named pipe and send [outbound] messages on the MODULE_TO_APP pipe.


override public function handleNotification(note:INotification):void
{
// Handle our Module->Application integration
switch( note.getName() )
{
case ModuleFacade.QUOTE_GENERATED:
// convert our *local* notification into the application format
var quoteMessage:Message = new Message(MortgageAppEventNames.LOAN_QUOTE_READY,null,
new Notification(MortgageAppEventNames.LOAN_QUOTE_READY,note.getBody(),note.getType()));
junction.sendMessage(PipeAwareModule.MODULE_TO_APP_PIPE,quoteMessage);
break;
}
}

override public function handlePipeMessage( message:IPipeMessage ):void
{
// Handle our Application->Module integration
var note:INotification = message.getBody() as INotification;
switch(note.getName())
{
case MortgageAppEventNames.REQUEST_FOR_LOAN:
sendNotification(ModuleFacade.QUOTE_REQUESTED,note.getBody(),note.getType());
break;
}

}

If the app was to load another module our diagram would become…
Pipes App with Two Modules

If your still have questions – just ask ๐Ÿ™‚

Loaded Module Dimensions – Width / Height

Ran across a problem regarding the display size of dynamically loaded modules today. The module was a subclass of ModuleLoader. The module would size to the minWidth / minHeight I had specified but would ignore width=”100%” for height=”100%”.

This Adobe Tech note states that your module should use ‘percentWidth’ and ‘percentHeight.’ I set that for the module and still no luck (probably because I subclassed ModuleLoader not Module for the time being).

What did work was to set the percentWidth / percentHeight in actionscript before I call addChild().


module.percentHeight = 100;
module.percentWidth = 100;
this.addChild(module);

Pipe Architecture

Here’s a working architecture for modular applications utilizing PureMVC pipes.

Pipe Architecture

This allows you to have modules that load modules that load modules, etc. The modules communicate to each other via Pipes.

The sample diagram illustrates a parent, child, grandchild relationship (An app that loads a module that loads module). You can of course, have multiple siblings.

PureMVC Pipes

I had a chance to work with Cliff Hall’s PureMVC ‘Pipes’ utility this week. Highly recommended.

If your interested in utilizing modules in your PureMVC projects, you owe it to yourself to take a look at the Pipes utility.

What’s needed to integrate a module?

The requirements are very light. You module should:

Implement IPipeAware
Create a JunctionMediator.

Thats it.

I took some time and refactored the Mortgage app to use the Pipes utility.

I ran into a small bump after unloading widgets. If I unloaded a widget and then clicked “Quotes”, I still received a loan quote from what should have been an unloaded module. I ended up subclassing the ‘TeeSplit’ class to allow disconnecting a single known IPipeFitting. This allowed me to ‘cleanup’ the dynamic modules properly.

That aside, the utility was very easy to work with – the plumbing metaphors really make things clear.

I found the utility to be quite flexible as well. I just wrapped up working on some utility classes that allow modules to load modules that load modules etc. Getting this to work with direct core to core communications was at best ‘messy.’ Using the pipes made this very clean and simple.

PureMVC + Lazily [late] Instantiated Components

One small caveat when working with PureMVC – If your [view] component is defined at design time, but not created at application startup you’ll need to defer the

facade.registerMediator( )

This might happen, for example, when your component resides in a viewstack.

A simple work around is to dispatch an event (make sure it bubbles) on the component’s creationCompelete.

creationComplete="dispatchEvent(new Event(CommonEvents.COMPONENT_INITIALIZED,true))"

In the ‘application level’ mediator, create an event listener for this event

viewComponent.addEventListener(
CommonEvents.COMPONENT_INITIALIZED,onComponentReady,false,0,true);

When the event is picked up you’ll have to determine which [lazy] component is ready

public function onComponentReady(event:Event):void
{
var comp:UIComponent = event.target as UIComponent;

switch(comp.id)
{
case "userSearch":
facade.registerMediator(new UserSearchMediator(comp));
break;
case "serviceRecord":
facade.registerMediator(new ServiceRecordMediator(comp));
break;
case "appToolbar":
facade.registerMediator(new AppToolbarMediator(comp));
break;
}

}

So, in short, we simply defer creating the component’s mediator until the view component is ready ๐Ÿ™‚

Securing AMFPHP 1.9 via Authentication

With the loss of the methodTable in AMFPHP 1.9, comes a loss of the easily defined ‘roles.’

Background

Roles, for those of you who aren’t familiar, allow you to ‘protect’ who can invoke your AMFPHP services. For example, you probably wouldn’t want the following function accessible to everyone


public function SetEmployeeSalary($amount)

Users are ‘authenticated’ in AMFPHP via a call to


Authenticate::login($username,$roles);

Where $roles is a comma delimited set of roles for the user. If you open up \core\shared\util\Authenticate.php you’ll find the login method


function login($name, $roles) {
if(!session_id())
{
session_start();
}
$_SESSION['amfphp_username'] = $name;
$_SESSION['amfphp_roles'] = $roles;
}

Authentication in AMFPHP 1.9

To utilize authentication in 1.9, create a function with the following signature in your service (class).


public function beforeFilter($function_called)

A quick peek in /core/shared/app/BasicActions.php and you’ll see that, should your service (class) define this function, AMFPHP will call it before invoking your function. If beforeFilter returns true, the function is invoked, otherwise a security error is thrown.

Here’s the simple approach I’ve taken..


public function beforeFilter($function_called)
{
$memberName = $function_called."Roles";
return (@$this->$memberName) ? Authenticate::isUserInRole($this->$memberName) : true;
}

So to secure any function, I simply define a member variable with the roles required.


var $SetEmployeeSalaryRoles = "admin,hr";
public function SetEmployeeSalary($amount)

My beforeFilter function looks to see if functionNameRoles exists, if it does, than the user must have a role found in functionNameRoles. If functionNameRoles does not exist, no authentication is required.

Two must haves for those โ€˜rigorousโ€™ developers out there.

I’ve come across two [free] tools I find indispensable when working under the Windows platform.

Task Arrange
Aqua Dock

Task arrange
Task Arrange
Task arrange allows you to change up, on the fly, the order of programs listed on the taskbar.

Aqua Dock
Aqua Dock Desktop
I’ve moved all of my desktop icons off my desktop and onto the dock. No need to worry about my icons being shuffled around after hooking up to a digital projector for presentations ๐Ÿ™‚