Get started with Project Zero and PHP

Build a simple Web application

Project Zero provides an environment for the rapid development of interactive Web applications based on popular Web technologies such as PHP. This tutorial demonstrates how easy it is to get started with Project Zero, from installing the development tools to constructing an Ajax Web 2.0 sample using PHP as the back-end scripting language. Exporting an application is covered on the way, together with examples of debugging and extending a Web 2.0 application.

Ed Slattery, Advisory Software Engineer, IBM

Ed Slattery photoEd Slattery has been working on the PHP team for the last year, developing the parser and scanner for the P8 runtime.



Judy Taylor, Software Engineer, IBM

Judy TaylorJudy Taylor is an Open Source software specialist in the PHP team and has a background in software testing.



October 2007 (First published 21 August 2007)

Before you start

Visit projectzero.org and join the community

Take a few minutes to peruse and get familiar with the Project Zero Web site. You can join the Project Zero community, contribute to the project, or join the discussion forum, where you can comment on the project through each stage of its development.

Prerequisites

This tutorial assumes only that you have a suitable Java™ Development Kit (JDK) installed on your machine. You need to be familiar with the concepts of PHP and JavaScript as well.


Introduction

Project Zero overview

Project Zero provides an environment for developing interactive Web applications quickly and simply. The objective of the project is to provide a complete infrastructure for Web deployment so that application developers are free to concentrate on the business logic. To show just how easy it is to get started, you will begin with an empty directory, installing all the required development tools and developing an Ajax Web 2.0 sample using PHP as the back-end scripting language, all within this tutorial. We use Eclipse as the development environment.

The instructions in this tutorial should be all you need, but you can find the full instructions for downloading and installing Project Zero for PHP at the Project Zero site.

Install Project Zero for PHP

Follow the steps in this list to install Project Zero for PHP:

  1. Create a new empty directory (for example, zero_example).
  2. Download the complete development environment for PHP within Eclipse. From the downloads page, you must select a build page (stable builds/S20070910-RC1 was selected for this tutorial, but that could change, so you should select the latest stable build). PLEASE NOTE that earlier versions, such as S20070611-M1, no longer work with the current release of Project Zero. Download the All-in-One PDT .zip file that is relevant to your operating system (for example, pdt-all-in-one-<release_name>-win32.zip) and unzip it in your zero_example directory. For example, if you are using Eclipse, you will have a directory called something like zero_example/<pdt_release_name>/eclipse.

Now that you have set up the development environment, you can install the Eclipse plug-ins that enable you to develop using PHP in Project Zero, as follows:

  1. Run the copy of eclipse.exe you find in the zero_example/eclipse directory, and when asked, give it a new workspace name, such as zero_example/workspace.
  2. From the menu, select Help > Software Updates > Find and Install....
  3. In the resulting dialog, select Search for new features to install and click Next.

Now you can add a new remote site to search for software updates:

  1. Click New remote site and in the resulting dialog, give the site a name like Project Zero.
  2. Assign the new remote site this name: http://www.projectzero.org/update/zero.eclipse.php.latest
  3. Click OK and in the outer dialog, click Finish.
  4. In the search results dialog, select the whole Project Zero element in the tree and click Next.
  5. Accept the license agreement and click Next.
  6. Click Finish and Install All.

The Project Zero environment for PHP is now installed. You will be asked to restart Eclipse, and then the environment is ready to use. Now you can create a simple PHP application.


Developing applications

Application 1: MyFirstProject

This section gets you started with developing your first application. The first step is to create a new Zero project in Eclipse by following these steps:

  1. Select File > New > Project... and expand the Zero category in the dialog (see Figure 1).
  2. Select Project Zero PHP Application and click Next.
  3. Give your project a name (for example, MyFirstProject) and click Finish. Your project is now created.
Figure 1. The Project Zero category
The Project Zero category

Because you selected Project Zero PHP application, Zero already knows that you'll be using PHP, so it has placed a suitable php.ini file into the config directory of the project. See Listing 1 for an extract from the contents of this INI file. The lines shown in Listing 1 tell PHP to load the Zero extensions.

Listing 1. The Project Zero PHP extensions
extension = zero.php.ZeroExtension
extension = zero.php.JSONExtension
extension = zero.php.LoginServiceExtension
extension = zero.php.ACFExtension
extension = zero.data.php.QueryExtension
extension = zero.php.XMLExtension
extension = zero.php.NetworkExtension
extension = zero.php.URIUtilsExtension

Zero has also added in the required PHP dependencies to the ivy.xml file. If you double-click this file in the navigator, you'll see the zero.php dependency in the list. (For future reference, you can click Add here and examine the list of other modules that you could add.)

Now you have PHP enabled in Zero, and you have the Zero extensions enabled in PHP so the Zero runtime can call the P8 engine to handle the incoming data from Web applications. PHP can use the services of the Zero PHP extensions to get at the Zero Global Context.

The Zero Global Context is one of the keys to Zero development. Everything that is required from the client by the server can be located in the Global Context. (For more information, refer to the Zero documentation's Core Developer's Guide; see Resources for a link.)

The next step in the process is to create a simple PHP application to enter some data at the client side and read it at the server side using a PHP script.

Creating the PHP application

Before beginning, ensure that you are developing in the PHP perspective by checking the name in the top right corner of the window. If you are not in the PHP perspective, click the icon with a plus symbol on the top right corner of the window to change perspectives.

Next, follow these steps to get started:

  1. Expand the MyFirstProject directory.
  2. Right-click the public directory and create a new PHP file called MyFirstForm.php. Copy the code shown in Listing 2 into the form, overwriting the default PHP tags, and save it:
Listing 2. A simple form
<!--Input form with one field and a button-->
<html>
<head>
   <title>My First Form</title>
</head>
<body>
   <form name="input" action="/action.php" method="POST">
      <input type="text" name="item">
      <input type="submit" name="action" value="Post a message">
   </form>   
</body>
</html>

Note: The file extension was .php, but it does not actually contain any PHP; it is just HTML, and .html would have served just as well. The PHP script could be included in this form, but you are going to create another form called action.php to handle the post. Note that the line of code form action='action.php' tells the server which script handles the action.

Now create a second PHP file in the public directory called action.php, paste in the code from Listing 3, and save the file:

Listing 3. A simple PHP back end
<html>
<body>
<b>Processing your entry</b>
<?php

$method = get('/request/method');
echo "<p>The request was a $method</p>";

$keys = list_keys('/request/params', true);

echo "<p>Here is the data:</p>";

echo "<table cellspacing='0' cellpadding='0' border='1' >";
echo "<tr><td>Key</td><td>Values</td></tr>";

for ($i=0;$i<count($keys);$i++) {
  echo  "<tr><td>$keys[$i]</td>";
  echo "<td>";
  $value = get($keys[$i]);
  if (is_array($value)) {
  	 for ($j=0;$j<count($value);$j++) {
  	 	echo "$value[$j] ";
  	 }
  } else {
  	echo "$value";	
  }
  echo "</td>";
  echo "</tr>";
}

echo "</table>";
?>
</body>
</html>

The code in Listing 3 is a mixture of HTML and PHP code. The PHP code outputs some HTML but uses the values that were entered from the original form. The Project Zero parts of this form are the following lines:

Listing 4. Getting items from the Global Context
$method = get('/request/method');
$keys = list_keys('/request/params', true);
...
$value = get($keys[$i]);

The first line of listing 4 uses the get(), which is part of the Zero runtime that was included into PHP by adding the Zero extensions to the php.ini file. This method gets a single value from the global context. The second line shows the use of list_keys(), where the entry in the global context is a list of key/value pairs, which is the case for '/request/params'. The loop including line 3 of the listing is working through the keys received, getting a corresponding value, and printing it as an array or a string.

Running the PHP application

These two forms together are a complete Zero example application. Right-click the project name in Eclipse and select Run as > Project Zero Application; a Web server is started on port 8080 of your localhost. You can now go to a browser and direct it to http://localhost:8080/MyFirstForm.php, and you should see your input form. Enter some data, for example This is my zero project, and click the button. Now you should see your output form, with a table showing the data you entered (see Figure 2):

Figure 2. The sample output
The sample output

You can click the Back button in the browser to return to the input form and enter different data, which is displayed when you click post a message again. To stop the application running, click on the square red symbol in the console window.

A key to understanding Project Zero is knowing which data elements you can query and set from the Global Context (which is where the get() method is finding things) and how to use the other plug-ins such as data zero to store and retrieve data from databases.

Exporting the application

My .zip file did not appear in Eclipse

The .zip file is written to disk but is not an artifact generated by Eclipse, so Eclipse has not registered its presence yet. Right-click the project name and select Refresh.

Before exporting the project, you must stop the Zero server by clicking the red square in the title above the console tab. After you have stopped the server, follow the instructions here to begin exporting the application:

  1. Right click the project in Eclipse and select Export....
  2. Expand the Zero category and select Project Zero Export Wizard.
  3. Choose the name of the directory to export to and check the box to include your source.
  4. Finally, select Finish and your project is exported as a .zip file to the directory of your choice.

The .zip file is just a means of transporting the project. If you want to run it from the command line, you need to install the command line Zero runtime and unzip the project into its apps directory.

At this point, to deploy the application in a Zero server, follow the instructions in Project Zero documentation (see Resources) to get the command-line zero runtime. You'll need to follow the CLI installation instructions up to running "zero seed," which picks up the Zero core libraries. The remainder of the instructions in this section of the documentation cover installing samples and create the apps directory, so you can either continue and install the samples for later use or just create the apps directory yourself with Windows® Explorer. After you have completed these steps, return to this point in the tutorial.

Problems deploying?

If you get an error 500 loading the MyFirstForm.php, first check that you really have a php.ini file in your config directory. If you do not, find one from another sample project or find one in the directory where you installed PHP.

If you experience a failure to load the action form indicated by unknown method get(), check that you have the zero extensions defined in your php.ini file.

Now, follow these steps to run your application:

  1. Unzip the .zip file you exported from Eclipse into the <zerohome>/apps directory. This creates a directory structure under apps for your application. Depending on how you unzipped the .zip file, you may have a single application directory (for example, MyFirstProject) or a base directory containing that directory.
  2. You must change the directory to the base of your application (there must be a subdirectory called config) and type zero resolve
  3. Finally, type zero run. This should start the same server on port 8080 as you originally saw in Eclipse. Your browser should now be able to load your file MyFirstForm.php.
  4. To stop the server again, just press Ctrl-C at the command prompt.

Adding Ajax functionality

Application 2: Using Ajax and Project Zero in MyFirstDojoApp

Now that you have created a simple PHP application, it's time to see how easy it is to add Ajax functionality using JavaScript and Dojo to the next one. Begin with the following steps:

  1. First, create a new Zero application project in Eclipse by clicking File > New > Project....
  2. Select the Project Zero PHP application style and click Next.
  3. Give your project a name (for example, MyFirstDojoApp) and click Finish.

With this application, you'll also be using Dojo, so you need to tell Zero the following:

  1. Expand MyFirstDojoApp and the config directory.
  2. Open the ivy.xml file, and in the Zero Package Information pane, click Add....
  3. In the Dependency Selection window, look for the Dojo dependency (shown at the top of the list in Figure 3), and if present, go to step 8.
  4. If the Dojo dependency is not listed, click Manage Repository (see Figure 3).
  5. In the Manage Repository window, click Search (without entering any other data).
  6. After a few moments (Searching Repositories), you are presented with a list (see Figure 3b).
  7. Select the Dojo dependency, click Download, and then click Close.
  8. Select Dojo... in the Dependency Selection window and click OK. (You should see Dojo added to the list of dependencies in the Zero Package Information pane.)
  9. Save your change using the File > Save menu.
Figure 3. The Dojo dependency
The Dojo dependency
Figure 3b. The Manage Repository window
The Manage Repository window

Updating the Zero dependencies

All these dependencies, such as Dojo and PHP, are under version control. To make sure you have the latest versions, all you have to do is click the Update Dependencies button in the Eclipse toolbar or select Zero > Update Dependencies from the menu (see Figure 4).

Figure 4. Update dependencies
Update dependencies

Now let's create a JavaScript and HTML front end to the application.

In the public directory, create a new file called Example.html. Paste in the code from Listing 5 and save the file:

Listing 5. A small javascript front end
<html>
<head>
<title>Dojo Zero Example</title>
<style type="text/css">
 @import "dijit/themes/noir/noir.css";
 @import "dojo/dojo.css"
</style>
<script type="text/javascript" src="dojo/dojo.js" 
        djConfig="parseOnLoad: true"></script>
<script type="text/javascript">
dojo.require("dijit.form.Button");
dojo.require("dojo.parser");

function enterPressed() {
alert('The enter button was pressed');
}
</script>
</head>
<body>
<br/>
<br/>
Type your name then press enter: <input type='text' id ='name'/>
<br/>
<br/>
<br/>
<button dojoType='dijit.form.Button' onclick='enterPressed' >Enter</button>
</body>
</html>

The code shown in Listing 5 does not interact at all with the server at present; it just pops up a message saying "The button was pressed" if the Enter button is clicked. The code does not use the traditional onClick within the button but uses the Dojo events system to register a method to call upon loading of the page.

Test-driving Dojo

It's worth giving the application a trial run at this stage to make sure that the Dojo part of the scenario is behaving itself:

  1. Right-click the project name and select Run as... > Project Zero Application.
  2. Go to your browser and navigate to http://localhost:8080/Example.html.
  3. Example.html should be an input panel containing a button and an entry field (See Figure 5). Enter some text in the entry field and click the button. Verify that you get a pop-up message containing the text: "The enter button was pressed."
  4. At this point, you might want to Google Firebug, a Firefox extension, and install it into Firefox. Firefox lets you step though more complicated JavaScript files later.
  5. If you did see the input panel but did not see the message when you clicked, it is likely that Dojo is not being used. Check the font and shape of the Enter button (see Figure 5). Dojo controls are styled according to a template (in our case "noir") as shown in the page header; a normal system font and button shape would indicate that Dojo is not running. Recheck the dependency of your project on Dojo that you set up in the previous paragraph (see Figure 3).
Figure 5. The Dojo Button
The Dojo Button

Adding the PHP back end and completing the front end

Next, let's add some code to transmit the button-click to Zero and provide a small PHP script to pick it up and handle it:

  1. In the public directory, add a new file called ExampleResponse.php.
  2. Paste in the code shown in Listing 6 and save the file:
Listing 6. Another PHP Back end
<?php

$method = get('/request/method');
echo " The request was a $method ";

$keys = list_keys('/request/params', true);

echo "\n Here is the data: ";

for ($i=0;$i<count($keys);$i++) {
  echo  " Key: $keys[$i] value:";
  $value = get($keys[$i]);
  if (is_array($value)) {
  	for ($j = 0; $j <count($value) ; $j++ ) {
  		echo " $value[$j] ";
  	}
  } else {
  	 echo " $value ";
  }
}
?>

Listing 6 should look pretty familiar, having followed the first example shown in this tutorial. It just gets the message and returns the contents for display.

Next, go back to the Example.html and add the enterPressed function to bind with the ExampleResponse you created earlier:

Listing 7. enterPressed function corresponds with the PHP back end
function enterPressed()
{
    var deferred = dojo.xhrGet({
        url: "ExampleResponse.php",
        handleAs: "text",
        content: {name: dojo.byId('name').value},
        timeout: 5000, //Time in milliseconds
        handle: function(response, ioArgs){
            if(response instanceof Error){
                if(response.dojoType == "cancel"){
                     alert("Request cancelled.");
                }else if(response.dojoType == "timeout"){
                     alert("Request timed out.");
                }else{
                     alert(response);
                }
            }else{
               alert(response);
            }
        return response;
        }
});
}

The handler to display the alert is embedded in the definition of the Function enterPressed above. This replaces the call to dojo.io.bind which was used in the previous version of this article targetting Dojo 0.4.3.

Be sure to save all your work.

Now you should be able to go to your browser, refresh the Example.html page, enter some text in the name field, click the Enter button, and see the "request was a GET" message come back from the server (as shown in Figure 6):

Figure 6. The application
The application

The completed Zero Ajax application

Congratulations! You have now completed a Zero Ajax application. Perhaps it's not the most complete Web application you have ever written, but you have to admit that it really was easy.

Hopefully, everything on the server side went well, but what would you have done if it all went wrong? As an exercise, let's alter the PHP script to cause a fault and see how to debug it.

Debugging the PHP code

Alter the first line of the script to contain the same faulty code as Listing 8:

Listing 8. Faulty code
$method = get('/request/mathod');

There is no such element as mathod in the Zero Global Context, so you would expect bad things to happen. Save the change, then go back to the browser, refresh the Example.html page, and observe what happens when you click Enter this time. Hopefully, you will get a helpful pop-up telling you exactly the line of the script that failed, and the error found (see Figure 7):

Figure 7. The error message
the error message

Note: From the front-end handler code, you can see that the error reported was not flagged as type='error'. That type is used for errors encountered when contacting the server. This error was just a response from the server, which happened to contain details of a fault in the script.

Another useful tip is that the P8 engine logs errors too. You can set the log_errors flag in your php.ini to On and set the error_log flag to be a file name of your choice. Then the same error will be written to that file. You'll see how that looks when you get a real PHP syntax error, which we'll try now.

Make the changes to the php.ini file in the config directory, alter your mathod back to method, and add the contents of Listing 9 to the ExampleResponse.php file, anywhere within the PHP code:

Listing 9. A faulty line of PHP code
this is not a line of php

When you run the page again, you should see the error message and also get the same syntax error reported in your error log file. (By default, the log file appears in the root directory of your project. You may have to right-click the project name and select Refresh to see it.)

Don't forget to delete the bad line of PHP before continuing!

Keeping track of your mouse

Finally, just for fun, let's tell the server where your mouse is. The server will respond with the location to be placed into a text box. Sending every mouse movement might not be a very efficient use of the system, but it demonstrates the interactivity of Ajax.

To get Dojo to recognize the body of your page as a control and hence track mouse movements, you must give the body a name. You must also add the new widget for the returned result. The body section of your page should look something like Listing 10:

Listing 10. The new Widget
<body id="body">
<br/>
<br/>
Type your name then press enter: <input type='text' id ='name'/>
<br/>
<br/>
<br/>
<button dojoType='dijit.form.Button' onclick='enterPressed' >Enter</button>
<br/>
Mouse Position: <input type='text' id='pos'/>
<br/>
</body>

Next, add into the init() method the code to link the mouse movement handler with the event and save all your changes. Your init() method should look something like Listing 11:

Listing 11. Linking mouse movements on body
function init()
{
   var domElement = document.getElementById('body');
    
    dojo.connect(domElement, 'onmousemove',	
		function (evt)
		{
    		var deferred = dojo.xhrGet({
        	url: "MouseResponse.php",
        	handleAs: "text",
       		content: {x:evt.pageX , y:evt.pageY},
        	timeout: 5000, //Time in milliseconds
        	handle: function(response, ioArgs){
            if(!(response instanceof Error)){
        		dojo.byId('pos').value = response;
       		}
        	return response;
        }
		});
	}
    );}
    
dojo.addOnLoad(init);

Finally, add a mouse movement processing PHP script in the public directory and call it MouseResponse.php as in the code in Listing 11. Paste the contents of Listing 12 into the PHP file:

Listing 12. The PHP back end for mouse movements
<?php
$keys = list_keys('/request/params',false);
for ($i=0;$i<count($keys);$i++) {
  echo  "$keys[$i]=";
  $value = get('/request/params'.$keys[$i]);
  echo "$value";	
}
?>

You should now be able to run the page, and see the position update, as shown in Figure 8:

Figure 8. The application
The application

Close this page before you shut down the server; otherwise, you will receive an error message per mouse movement to deal with!


Summary and next steps

What you've accomplished

In this tutorial, you:

  • Installed the Eclipse Development Environment for PHP.
  • Installed the Project Zero environment for PHP development in Web 2.0.
  • Developed an application with a simple HTML form and a PHP back end.
  • Exported the application and ran it from the Zero command line.
  • Developed a second PHP application that combines JavaScript with HTML for the front end.
  • Created some errors and debugged them.
  • Extended the Ajax application with an extra callback and a new Dojo widget.

What's next?

Now that you have completed a small Ajax Zero application, you can expand your use of the Dojo library and PHP back-end scripting. Why not combine these tools with the Data Zero component and build a real data retrieval system using Apache Derby? The Employee Demo PHP sample supplied with Project Zero is a good place to start. The Project Zero Documentation link in the Resources section will take you to the Project Zero demos.

If you would like to learn more about the Zero Global Context and other relevant topics such as Resource (REST) Handling, see the Project Zero Developer's Guide in the Resources.

We hope the exercises in this tutorial have been helpful to you in getting started with Project Zero. Be sure to visit projectzero.org if you want to get involved with this growing community. Check back with developerWorks often because we are planning to feature even more Project Zero content.

Resources

Learn

Get products and technologies

  • Download Eclipse, the platform used in this tutorial.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Web development on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Web development, Open source
ArticleID=248901
ArticleTitle=Get started with Project Zero and PHP
publish-date=10212007