How To Use J-AMFPHP

Here you will find out how to build and test an AMF service inside a Joomla! 1.5 (and above) installation using J-AMFPHP.

UPDATE: This post is still helpful even if
you were not aware of the advantages of
Adobe's Action Message Format (AMF) over XML, REST, etc.

Let’s say you are quite comfortable with building extensions for your Joomla! projects and you now want to take them to the next level by integrating them with Adobe Flex / AIR / Flash.

I assume that you have some basic knowledge of Flex and AIR and you know about all the advantages they can bring to your web applications, and that you know about the advantages of communicating with your remote applications via Adobe’s AMF protocol instead of XML or Web Services (i.e. better data exchange performance, especially for large datasets).

You probably also know about the wonderful AMFPHP script that enables you to leverage Adobe’s powerful AMF protocol for your PHP applications.

If this is you, then you probably know that an AMFPHP extension has been made available by Anthony Mclin under the guise of J-AMFPHP. The great thing about it is that it exposes your whole Joomla! environment to speak AMF with your Flex / AIR applications.

Fantastic!

You think to yourself.

Now I can build Flex and AIR applications for Joomla!
But wait a minute! I have downloaded and installed J-AMFPHP but I have no clue of how it works with Joomla!

Don’t worry, I went through the exact same thing and I want to save you the trouble of jumping through hoops in getting Joomla! to talk to your Flex / AIR environment.

Getting Ready

First, let’s have a look at the J-AMFPHP folder locations that we will be focusing on within your Joomla! folder structure:

[web-root]
    |__________[administrator]
            .........
               [amfphp]
            .........
               [plugins]
                   |______[j-amfphp]

The first folder, [amfphp] contains your gateway script just like you will find in the AMFPHP code. The AMF service browser is missing from the J-AMFPHP installation. I suppose this is for security reasons, however, for testing purposes the service browser is indispensable in testing your Joomla! AMF service code.

If you have not done so, please download the latest version of AMFPHP from SourceForge and extract the [browser] folder from the downloaded zip archive into your [amfphp] folder in Joomla! We will use the service browser to test our sample AMF service that we will build shortly.

UPDATE: Important - if you launch your service browser at this
stage you will get a faultCode = “AMFPHP_CLASSPATH_NOT_FOUND” error.

That's because the service browser needs an additional step to work properly.
Here's what you should do.

Find the [services] / [amfphp] folder inside your downloaded AMFPHP zip archive and extract this folder to [plugins] / [j-amfphp] in your Joomla! installation.

The service browser files should only be used in development environment. Leaving them in place in your production environment will allow anyone to view your AMF service composition, please remember to remove them before you go live.

Time For Action

Let’s get cracking and build our first AMF service class in Joomla!

Let’s name our service class “HelloJoomla” , which is a spin on the classic “Hello world!” application.

Under the [plugins] / [j-amfphp] folder in Joomla!, create a new folder named [hello_joomla] and underneath that create a file named “HelloJoomla.php”. This file will contain your AMF service class code.

Let’s run a little test to make sure that we are still on track before we dive into coding the service class.

Launch your web browser and point to:

http://url/to/your-joomla-installation/amfphp/browser/index.html (e.g. http://localhost/amfphp/browser/index.html)

The typical bluish Flex background should come up. After loading you should see two items on your leftmost panel i.e.

[+] amfphp
[+] hello_joomla

Clicking on the [+] sign next to the “hello_joomla” item will show something like (c) HelloJoomla.

So far so good. We’re ready to rumble.

*If you do not get these results, then you should step back and see whether you went through everything correctly.

Coding The AMF Class

Fire up your favourite code editor and open [plugins] / [j-amfphp] / HelloJoomla.php for editing.

Insert the following code:

<?php

//make sure this request comes from within the joomla framework
defined( '_JEXEC' ) or die( 'Restricted access' );

/**
 * An example "Hello World" class for AMFPHP.
 * Whatever you type here will show up in your AMFPHP browser
 * It is good practice to document your class and functions
 * (methods) this way to make it easier on anyone that
 * might want to use your code later, yourself included.
 */

class HelloJoomla
{
    /**
    * A basic function to demo AMFPHP Services
    * Takes in your name as a parameter and
    * returns a greeting message with your name on it
    * @param Name
    * @returns A text string with a greeting message
    */
    public function greetMe($name) {
        $text = "Hello ". $name .", you have just created your ";
        $text .= "first Joomla AMF service for Flash/Flex Remoting.";
        return $text;
    }
}
?>

As you can see, this is exactly the same way in which you code your PHP classes elsewhere!
All your wonderful “J” methods are now accessible from here e.g.

$db =& JFactory::getDBO();

Lastly, go to your web browser again and open / refresh
http://url/to/your-joomla-installation/amfphp/browser/index.html

Drill down to click on (c) HelloJoomla. You will see your “greetMe()” method on the right hand pane. Note how the comments that you included in your PHP code show up .

Type in your name in the space provided and click on “call”. Watch for the output underneath.

You’re unstoppable now! Your AMF gateway is up-and running. Your gateway access url from within your Flex / Flash / AIR environment will be

http://url/to/your-joomla-installation/amfphp/

Have fun integrating your Joomla! environment with Flex, Flash, And AIR!

Update: Create a "HelloJoomla" Adobe AIR Application in HTML and JavaScript  link
  • http://www.tandolin.co.za Figo

    @Bio

    Please accept my sincerest apologies for taking so long to answer you.

    Your question goes to the very heart of why I haven’t been speeding up on Joomla an AMF for a while.

    Any joomla method that sometimes returns a $this->setRedirect or JApplication redirect (e.g. on incorrect credentials or as a notification message) breaks the communication between Joomla and your AMF enabled app.

    That’s because the desktop app (and the AMF protocol itself) doesn’t know what to do with a return value of (e.g. JError::raiseError(…)).

    Sadly the implications are that there needs to be a parallel method re-written for every single Joomla one that tends to redirect. An impractical and monumental task.

    How have you managed to work around this issue?

  • Pingback: Behind the scenes | Figo Mago

  • Bio

    Hello Figo,

    thanks for this article, it is what i am searching for, but i have a question on the authentication service (plugin).
    when i use the service browser to test the login method, i’ll get an error message:

    (Object)#0
    message = “faultCode:INVALID_AMF_MESSAGE faultString:’Invalid AMF message’ faultDetail:’JError Application Instantiation Error
    ‘”
    name = “Error”
    rootCause = (null)

    if i call the login method from my flex application, i’ll get the Error #2044: NetConnection.Call.BadVersion

    i think the BadVersion error is because oft the JError, which is fired at JFactory::getApplication

    it seems there is no instance (global $mainframe) of the application, but i dont know it really.

    the other methods from the JoomlaUser.php Service do their job well.

    i am really confused about that and hope you can help me.

  • http://www.routerbits.us Edward M.

    Hello admin, I notice your blog post from mixx and I read some of your several other content.They’re great. Please keep working a great work.

  • http://www.computerid.com.br Roni

    Hello Mads.
    In this class I did the replace from “eregi_replace” to “preg_replace”. The method stayed like this:

    function cleanComment($comment){
    $comment = str_replace(“/**”, “”, $comment);
    $comment = str_replace(“*/”, “”, $comment);
    $comment = str_replace(“*”, “”, $comment);
    $comment = str_replace(“\r”, “”, trim($comment));
    $comment = preg_replace(“`\n[ \t]+`U”, “\n”,trim($comment));
    $comment = str_replace(“\n”, “\\n”, trim($comment));
    $comment = preg_replace(“`[\t ]+`U”, ” “,trim($comment));
    $comment = str_replace(“\”", “\\\”", $comment);
    return $comment;
    }

    I hope I helped you.

  • http://www.viezel.dk Mads

    arh.. I was to quick to post…
    the solution is here: http://matthiasvanneste.wordpress.com/2009/09/18/php-5-3-0-and-amfphp/

    Thanks again for sharing!

  • http://www.viezel.dk Mads

    Hi, thanks for sharing

    I overcome the CLASSPATH error by downloading the original AMFPHP and copy the DiscoveryService.php file to:

    /joomlainstallfolder/plugins/j-amfphp/amfphp

    Now I can access the browser. I can see the services, but when I try to access them, I get the following error:

    Error retrieving service info:

    Function eregi_replace() is deprecated
    /customers/klubsummit.com/klubsummit.com/httpd.www/joomla/libraries/amfphp/core/shared/util/MethodTable.php on line 505

    I compared the MethodTable.php with the original AMFPHP, it seems to be the same…
    Someone got a solution?

  • http://www.computerid.com.br Roni

    Hi Figo!

    Very useful tutorial. I´m trying to customize the Joomla service with a Flex interface, using J-AMFPHP. The userLogin method I already got it. But now I´m trying to implement search method, for instance. Have you implemented another method besides those from the examples?

    Thanks

  • http://www.tandolin.co.za Figo

    @Tom: Ok. I get the cause of the problem now. A browser based session (e.g. authenticating a Joomla session via your web browser) has nothing to do with authenticating via AMF. These are two completely different protocols (leading to two completely different web sessions).

    What you need to do is authenticate via a remote service call, and then execute privileged commands via the same remote sessions. Authenticating via a web browser based session and then trying to maintain that same session through an AMFPHP remote call will simply not work.

  • http://iregatta.net tom

    Figo,

    Try this:

    Open joomla front page and log in as a user (any).

    Then using any remote service call:

    $user =& JFactory::getUser();

    $user will reflect a non-logged in user.

    T

  • http://www.tandolin.co.za Figo

    @tom: Are you by any chance using the example service class provided in addition to the J-AMFPHP plugin? Using that I had no problem with the issues you are experiencing. Can you drop me the code for your service class via my contact form so we can try to see where the problem is?

    @Anthony: Thank you for pointing out my error. I’m relieved because the availability of the service browser bundled together with the J-AMFPHP plugin eliminates some unnecessary steps and simplifies the whole setting up process. I will edit this post to reflect this. Thanks again for this and for creating such a wonderful piece of software.

  • http://www.anthonymclin.com Anthony McLin

    Hi Figo, thanks for posting this tutorial, I hope it has helped people out.

    I did notice one mistake though, you said that the AMFPHP browser is not included in the J-AMFPHP package. This is not true, if you’ve installed J-AMFPHP, you can access the service browser at [joomla location]/components/com_amfphp/browser

  • http://www.iregatta.net tom

    Figo,

    While using the gateway, I don’t seem to be able to get the user variables.

    In the PHP script,

    $user =& JFactory::getUser();

    Will result in a guest user, even if the user has logged in. Is there any way to get the user variables?

    Tom

  • handoyo

    I get it Figo..Thanks anyway.. ^_^

  • handoyo

    Ok Figo,thanks..By the way,do we have to create a plugin for joomla first to connect jamfphp into joomla?

    • http://www.tandolin.co.za Figo

      @Handoyo

      Once you’ve installed the core J-AMFPHP extensions into Joomla, it is not necessary to package your AMF service classes into Joomla plugins ( like the “J-AFMPHPAuthenticationService” mentioned earlier ) whilst developing your app. You can simply create the service class(es) inside your “plugins/j-amfphp” folder.

      The ability to package your service classes into plugins is a handy one however,when you want to distribute your work. It also gives you the flexibility to group your service classes into several Joomla plugins.

  • handoyo

    Hi Figo,suppose i want to login into joomla,should i use the joomla login system or create own class?Thanks..Also looking forward to an example of login if you don’t mind.. ^_^

  • Pingback: New Online Portfolio And Mini-Rant | Figo Mago

  • http://iregatta.net tom

    Figo,

    I’m getting this working, but I’m getting generic objects instead of typed objects. The tutorial you suggest i read:

    http://www.adobe.com/devnet/flex/articles/flex_php_04.html

    has definitions to be put in an index.php file. What is the equivalent in Joomla?

    The lines needed are:

    setClass(“MyService”);
    //Mapping the ActionScript VO to the PHP VO
    //you don’t have to add the package name
    $server->setClassMap(“VOAuthor”, “VOAuthor”);
    echo($server -> handle());
    ?>

    Where do these belong in the Joomla case?

    Thanks,

    Tom

    • http://www.tandolin.co.za Figo

      Hey @Tom,

      Sorry for the late reply. I had a look at your tutorial url and found that it is for connecting Flex to the Zend Framework via AMF. (http://www.adobe.com/devnet/flex/articles/flex_php_04.html)

      The equivalent in Joomla would be closer to the tutorial pointed out by @François Greze, i.e. http://corlan.org/2008/10/10/flex-and-php-remoting-with-amfphp/.

      You would setup your files exactly as shown in the tutorial, except that your “MyService.php” class would not need you to define your db connection credentials as global variables inside the class file. You would not need to define them at all.

      Your methods inside “MyService.php” (i.e getData() and saveData()) would use native Joomla! methods instead of standard PHP.

      e.g.

       public function getData() {
              //connect to the database.
              $mysql = & JFactory::getDBO();
              //retrieve all rows
              $query = "SELECT id_aut, fname_aut, lname_aut
                        FROM #__authors_aut
                        ORDER BY fname_aut";
              $mysql->setQuery($query);
              $result = $mysql->loadObjectList();
      
              $ret = array();
              foreach ($result as $row) {
                  $tmp = new VOAuthor();
                  $tmp->id_aut = $row->id_aut;
                  $tmp->fname_aut = $row->fname_aut;
                  $tmp->lname_aut = $row->lname_aut;
                  $ret[] = $tmp;
              }
              return $ret;
          }
      
  • handoyo

    Hi,i want to ask.Is it possible to login from adobe air application into joomla based website?And manage the content?Thanks…

    • http://www.tandolin.co.za Figo

      @handoyo

      My apologies for taking so long. Glad you asked that question. It’s certainly possible to login from an Adobe AIR application and manage your joomla content. In fact you can write an AIR app to mimic the whole functionality of your Joomla backend.

      Certainly possible, but no mean feat. I was thinking of adding an article, section and category manager to my upcoming AIR app for Joomla to begin with.

  • http://www.suhreedsarkar.com Borhan Uddin

    Hi, Figo. Thanks fr this nice tutorial. I tried to follow what you have instructed here. But still getting following error message while browsing http://localhost/flash/amfphp/broswer/index.php:
    mx.rpc::Fault)#0
    errorID = 0
    faultCode = “AMFPHP_CLASSPATH_NOT_FOUND”
    faultDetail = “C:\wamp\www\flash\libraries\amfphp\core\shared\app\BasicActions.php on line 25″
    faultString = “The classpath folder {C:\wamp\www\flash\plugins\j-amfphp/amfphp\DiscoveryService.php} does not exist. You probably misplaced your service.”
    message = “faultCode:AMFPHP_CLASSPATH_NOT_FOUND faultString:’The classpath folder {C:\wamp\www\flash\plugins\j-amfphp/amfphp\DiscoveryService.php} does not exist. You probably misplaced your service.’ faultDetail:’C:\wamp\www\flash\libraries\amfphp\core\shared\app\BasicActions.php on line 25′”
    name = “Error”
    rootCause = (null)
    I googled and found that many others are also getting this kind of message. Can you please help with a solution to this?

    • http://www.tandolin.co.za Figo

      @Hussain Thanks for the positive feedback.

      @Borhan Thank you for pointing out the prevalence of the “faultCode = “AMFPHP_CLASSPATH_NOT_FOUND”” errors. This was mentioned on this post but I did not articulate it. I’ve updated the related paragraph to better explain the solution to your problem. You can get to that area of this post by clicking here

  • Hussain

    I’m really grateful and very impressed by this plug in… It is a great thing, a powerful tool, this can revolutionize developing web applications… Just imagine to have all the beauty and the power of Joomla CMS inside Flex and vice versa…

    I thank you and thank Amthony Mclin..

    My best regards
    Hussain

  • http://www.tandolin.co.za Figo

    I’ve added a new related post

    Creating an AIR application to communicate with Joomla over AMFPHP (J-AMFPHP).

    http://figo.tandolin.co.za/adobe-air/building-a-j-amfphp-air-application-in-htmljs.htm

  • Pingback: Building A J-AMFPHP AIR Application in HTML/JS | Figo Mago

  • François Greze

    hi ,
    for the link : http://www.amfphp.org/ is the correct one [^.-]

    And to acces to acces hellojoomla in flex , you should watch those tutorials :

    http://www.adobe.com/devnet/flex/articles/flex_php.html?devcon=f1
    http://corlan.org/2008/10/10/flex-and-php-remoting-with-amfphp/

    Even if it ‘s talking about using “zend_amf’ for the server part , the flex part still the same …

    hope it’s helping you .

    Happy coding …

    FG

    PS: HI , Mister Figo :)

    • http://www.tandolin.co.za Figo

      @François thank you for the links. They are really helpful.

      @Galo I know I promised to have something up by now. I’ve made some progress but I can’t really talk much about the two projects until I release the beta versions. Soon, I promise ==)

      @Tom thanks for pointing out the amfphp.org link error. Updated ==)

  • http://iregatta.net tom

    Hi,

    Could you show how to acces hellojoomla in flex?

    Also, your link for AMFPHP seems broken.

    Thanks

    Tom

  • http://www.vecuador.com galo hernandez

    hi Figo, i am back he he, hey bro i hope you launch some air/joomla! stuff soon it will be so great, i am still havin some trouble about publishing flex into joomla, i hope you have found something and i beg you to share it, thanks a lot again

  • Werther

    Hi Figo.
    I hope u can help me.
    i try to follow your guide, but when I try to display a browser page, I have an error message in a window (under the browser flex page) with these lines:

    (mx.rpc::Fault)#0
      errorID = 0
      faultCode = "Client.Error.MessageSend"
      faultDetail = "Channel.Connect.Failed error NetConnection.Call.Failed:
                        HTTP: Failed"
      faultString = "Send failed"
      message = "faultCode:Client.Error.MessageSend faultString:'Send failed'
                      faultDetail:'Channel.Connect.Failed error
                      NetConnection.Call.Failed: HTTP: Failed'"
      name = "Error"
      rootCause = (Object)#1
        code = "NetConnection.Call.Failed"
        description = "HTTP: Failed"
        details = "http://www.domain.com/amfphp/gateway.php"
        level = "error"
    

    you have an idea?

    thanks in advance

    • http://www.tandolin.co.za Figo

      @Werther

      I assume you get this error when you try to launch your application via FlexBuilder into your web browser. If so, it looks like your AMF gateway is not set inside your flex program.

      Try changing “http://www.domain.com/amfphp/gateway.php” in your Flex program to your installed AMF gateway.

      Feel free to give me a shout if I did not understand your question correctly =)

  • François Greze

    HI Figo ,

    No probleme for the delay..: )

    I’ll check your post for sure .

    On my side , I did find some solution and it’s works nicely now…

    My main concern was in fact the class mapping process between flex and PHP.

    Happy coding Mister Figo !

  • François Greze

    Hi,

    Thank you for your time and for sharing this “tutorial”… as you said ” It save me a lot of time… ” (already loosed by the way ^^)

    I have a question for you if you don’t mind :

    Have you already set up a component with it in Joomla! ? did you bookmark some magic ressources about it or exemple ?

    Anyway THX again !!
    Chears form Paris France .

    François

    • http://www.tandolin.co.za Figo

      @François: Sorry for the late reply. I have a couple of Joomla/Air projects in the pipeline. I thought I would have one out by now but other project work eeps getting in the way.

      I plan to post a few more links and tutorials on Joomla/Air because I think they make a wonderful combination.

      You will be the first to know (eta 3 weeks or so). :D

  • Galo Hernandez

    Hi Figo, i am a developer from Ecuador-SouthAmerica, i want to thank you very much about this great article it help a lot because exactly as you said i was lost with the j-amfphp component and plugin, it works perfectly following your instructions.

    i just have one question, now that everything works, how can i, lets say, put flex in the front page of joomla and make it works, this is my main objective of my research, i like you said, want to join this 2 wonderful tech, thank you very much for your support and help,

    Galo.

    • http://www.tandolin.co.za Figo

      Galo, I’m glad that you found the post useful.

      I’m not sure that I fully understand your question. I suppose you want to run a website with a Flex front-end and a Joomla! backend?

      If so, there are a couple of ways to do that. I can think of one simple but not so elegant method you can use.

      You can install your Joomla! installation into a sub-directory under your web-root directory (e.g. [web-root] ——–>[joomla] ), then publish your Flex application in the [web-root] directory.

      Otherwise you can write your Flex application to be a Joomla! component/module if you want to render it within your Joomla! templating system.

Recent Tweets