DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jonnie has posted 12 posts at DZone. View Full User Profile

Creating A Service Class For Amfphp

09.21.2008
| 5017 views |
  • submit to reddit
        Here is a very helpful script for creating a connection between your Flex/Flash application and amfphp. 

We are mimicking the available methods that are on our server. You could easily add methods to both ends to create more functionality.

Code is used as follows:


package com.jonniespratley.snippr.services
{
    import com.jonniespratley.snippr.model.ModelLocator;
    import com.jonniespratley.snippr.vo.SnippetVO;
    
    import flash.net.NetConnection;
    import flash.net.Responder;
    import flash.utils.ByteArray;
    
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.controls.Image;
    import mx.controls.Text;
    import mx.core.Window;
    import mx.rpc.events.ResultEvent;
    
    /**
     * This file is for use without! using the services-config.xml file 
     * @author Jonnie
     * 
     */    
    public class SnipprService
    {
        private static var _service:NetConnection;
        private var model:ModelLocator = ModelLocator.getInstance();
        
        //Here we are creating a new connection to our amfphp service, when this is instantiated, it connects to our service
        public function SnipprService()
        {
            _service = new NetConnection();
            _service.connect( "http://localhost/snippr/amfphp/gateway.php" );
        }        
        
        
        /* ***************************************
        *** Service Calls
        *****************************************/
        
        //Here we are calling the getSnippets on our server (amfphp) and setting the result and fault handlers
        public function getSnippets():void
        {
            _service.call( "snippr.SnipprService.getSnippets", new Responder( snippetResultHandler, snipprFaultHandler ) );
        }
        
        //We take one argument here, and that is a snippet, because our server (amfphp) is expecting a snippetVO
        public function saveSnippet( snippet:SnippetVO ):void
        {
            _service.call( "snippr.SnipprService.saveSnippet", new Responder( snippetSavedHandler, snipprFaultHandler ), snippet );
        }
        
        //We take one argument here, and that is the id of the snippet we are wanting to remove
        public function removeSnippet( snippet_id:uint ):void
        {
            _service.call( "snippr.SnipprService.removeSnippet", new Responder( snippetRemoveHandler, snipprFaultHandler ), snippet_id );
        }
        
        //We take two arguments here, one is a byte array and the other is the filename of the file
        public function takeSnapshot( bytes:ByteArray, filename:String ):void
        {
            _service.call( "snippr.SnipprService.takeSnapshot", new Responder( snapshotResultHandler, snipprFaultHandler ), bytes, filename );
        }        
        
        /* ***************************************
        *** Result and Fault Handlers
        *****************************************/
        
        //Here we are handling the result coming back as an array of snippets, then we add our snippets to our model        
        private function snippetResultHandler( data:Array ):void
        {            
            model.snippetCollection = initVO( data );
        }
        
        private function snapshotResultHandler( data:Object ):void
        {
            var result:ResultEvent = data as ResultEvent;
                        
            /* This is just for some fun */
            var w:Window = new Window();
                w.width = 600;
                w.height = 500;
                w.layout = "vertical";
                
            var i:Image = new Image();                                
                i.source = data.result;
                
            var t:Text = new Text();
                t.text = "Nice shot, and nice app, Here is the link for the screenshot.\n " + data.result;
                
                w.addChild( i );
                w.addChild( t );            
                w.open();            
                
            trace( data.result );
        }
        
        //Helper for the result
        private function initVO( resultArray:Array ):ArrayCollection
        {
            var tempArray:ArrayCollection = new ArrayCollection();
            
            for ( var s:String in resultArray )
            {
                tempArray.addItem( new SnippetVO( resultArray[s] ) );
                
            }
            return tempArray;
        }
        
        //Here we are handling the result and adding it to the value of serviceResponse in our model
        private function snippetSavedHandler( data:Object ):void
        {
            ModelLocator.getInstance().serviceResponse = data.toString();
        }
        
        /*
        Here we are handling the result that is being returned, which will be the id of the removed snippet, and 
        removing it from our model, at the snippet index
        */
        private function snippetRemoveHandler( data:Object ):void
        {
            getSnippets();
        }
        
        //Here we are alerting the user that there was an error connection to our server
        private function snipprFaultHandler( fault:Object ):void
        {

            Alert.show( "There was an error connecting to the server.", "Snippr Service Error" );
        }        
    }        
}

Here is the value object for this class

package com.jonniespratley.snippr.vo
{	
	[RemoteClass(alias="vo.SnippetVO")]
	
	/**
 	* VOs are used to create a layer of business objects that can be 
 	* transferred between tiers, instead of using records, results sets, and datasets.
 	*/
	[Bindable]
	public class SnippetVO
	{
		public var snippet_id:int;
		public var snippet_title:String;
		public var snippet_code:String;
		public var snippet_type:String;
		public var snippet_created:String;
		public var snippet_user:String;		
		
		/**
		 * Helper function for building the data. 
		 * @param source
		 * 
		 */		
		public function SnippetVO( source:Object = null )
		{
			if ( source != null )
			{
				for ( var item:String in source )
				{
					try 
					{
						this[item] = source[item];
					}
					catch ( error:Error )
					{
						throw new Error( "SnippetVO: " + error );
					}
				}
			}
		}
	}
}