Wild Web Works Inc.

April 1, 2009

Database Connection Class – Flex,PHP,Postgres

We reuse our database connection many times throughout our code.  The call is a bit complex and continually copying it was a waste of space.  We came up with a class. This is the DBConnection.as page in its entirety.

package utility
{
	// Import
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.RemoteObject;
 
	public class DBConnection
	{
	// Create Remote Object for connection to PHP then Postgres for records ArrayCollection
	public var dbConnect:RemoteObject = new RemoteObject;
 
// Data
	//pass in parameters for specific record array request with or without 
	//array of parameters to include in function call to PHP
	public function loadRecords(dest:String, srce:String, phpCall:String, resultFunc:Function, args:Array):void{
		dbConnect.destination = dest;
		dbConnect.source = srce;
		dbConnect.getOperation(phpCall).addEventListener(ResultEvent.RESULT, resultFunc);
		dbConnect.addEventListener(FaultEvent.FAULT, faultHandler);
		if(args.length > 0){
		 dbConnect.getOperation(phpCall).arguments = args;
		}
		dbConnect.getOperation(phpCall).send();
	}
 
	private function faultHandler(event:FaultEvent):void{
			Alert.show(event.fault.faultString, event.fault.faultCode.toString());
		}
 
	}
}

The call is then very simple every time you need it. You can leave the array empty if you have no parameters to pass, or put them all in. Here’s an example of each.

//Load Records - WITH PARAM & VARIABLES	
	public function getPeopleByRef(r_id:uint, r_short:Boolean):void
	{	
		var dbConn:DBConnection = new DBConnection();
		dbConn.loadRecords("zend","People","getPeopleByRef", resultGetPeople,[r_id]);
	}
 
//Load Records - NO PARAMS	
	private function getContracts():void{
		var dbConn:DBConnection = new DBConnection();
		dbConn.loadRecords("zend","Contract","getContracts",resultGetContracts,[]);
	}

This works great every time.

1 Comment »

  1. Awesome… This is exactly what I needed.

    Thanks!

    Comment by Ron Rebennack — October 5, 2009 @ 11:01 am

RSS feed for comments on this post. TrackBack URL

Leave a comment