Editor's note: IBM® WebSphere® sMash and IBM WebSphere sMash Developer Edition are based on the highly acclaimed Project Zero incubator project. Project Zero is the development community for WebSphere sMash and will continue to offer developers a cost-free platform for developing applications with the latest builds, the latest features, and the support of 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. This article 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.
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, this article will walk you through an exercise in which you will begin with an empty directory, install all the required development tools, and develop an Ajax Web 2.0 sample using PHP as the back-end scripting language. Eclipse is used as the development environment.
The instructions in this article should be all you need to complete the exercise, but you can find the full instructions for downloading and installing Project Zero for PHP at the Project Zero site (see Resources).
Now, let's get the exercise started by following the steps in this list to install Project Zero for PHP:
- Create a new empty directory (for example,
zero_example). - Download the complete development environment for PHP within Eclipse (see Resources for a link). Note: From the downloads page, you must select a build page (stable builds/S20070910-RC1 was selected for this exercise, but that could change, so you should select the latest stable build). Important: 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:
- 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. - From the menu, select Help > Software Updates > Find and Install....
- 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:
- Click New remote site and in the resulting dialog, give the site a name like
Project Zero. - Assign the new remote site this name:
http://www.projectzero.org/update/zero.eclipse.php.latest - Click OK and in the outer dialog, click Finish.
- In the search results dialog, select the whole Project Zero element in the tree and click Next.
- Accept the license agreement and click Next.
- 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 Application 1: MyFirstProject
The first step to get started with developing your first application is to create a new Zero project in Eclipse, as follows:
- Select File > New > Project... and expand the Zero category in the dialog (see Figure 1).
- Select Project Zero PHP Application and click Next.
- Give your project a name (for example,
MyFirstProject) and click Finish. Your project is now created.
Figure 1. 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.
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:
- Expand the MyFirstProject directory.
- 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 = zget('/request/method');
echo "<p>The request was a $method</p>";
$keys = zlist('/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 = zget($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 = zget('/request/method');
$keys = zlist('/request/params', true);
...
$value = zget($keys[$i]);
|
The first line of Listing 4 uses the zget(),
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
zlist(), 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.
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):
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 from 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.
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:
- Right click the project in Eclipse and select Export....
- Expand the Zero category and select Project Zero Export Wizard.
- Choose the name of the directory to export to and check the box to include your source.
- 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 exercise.
Now, follow these steps to run your application:
- 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.
- You must change the directory to the base of your application (there must be a
subdirectory called config) and type
zero resolve - 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. - 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:
- First, create a new Zero application project in Eclipse by clicking File > New > Project....
- Select the Project Zero PHP application style and click Next.
- 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:
- Expand MyFirstDojoApp and the config directory.
- Open the ivy.xml file, and in the Zero Package Information pane, click Add....
- 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.
- If the Dojo dependency is not listed, click Manage Repository (see Figure 3).
- In the Manage Repository window, click Search (without entering any other data).
- After a few moments (Searching Repositories), you are presented with a list (see Figure 3b).
- Select the Dojo dependency, click Download, and then click Close.
- Select the latest Dojo in the Dependency Selection window and click OK. ( I used Dojo 0.9, but there are later versions now.) You should see Dojo added to the list of dependencies in the Zero Package Information pane.
- Save your change using the File > Save menu.
Figure 3b. The Manage Repository window
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.
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:
- Right-click the project name and select Run as... > Project Zero Application.
- Go to your browser and navigate to http://localhost:8080/Example.html.
- 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."
- 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.
- 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).
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:
- In the public directory, add a new file called
ExampleResponse.php. - Paste in the code shown in Listing 6 and save the file:
Listing 6. Another PHP back end
<?php
$method = zget('/request/method');
echo " The request was a $method ";
$keys = zlist('/request/params', true);
echo "\n Here is the data: ";
for ($i=0;$i<count($keys);$i++) {
echo " Key: $keys[$i] value:";
$value = zget($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 exercise. 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 a 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):
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 a sub-exercise, let's alter the PHP script to cause a fault and see how to debug it.
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 8:
Listing 8. 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 9:
Listing 9. 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 9. Paste the
contents of Listing 10 into the PHP file:
Listing 10. The PHP back end for mouse movements
<?php
$keys = zlist('/request/params',false);
for ($i=0;$i<count($keys);$i++) {
echo "$keys[$i]=";
$value = zget('/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:
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 exercise, 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.
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 listed in the Resources.
We hope this exercise has 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 for frequent updates to the Project Zero library.
Learn
- If you'd like to join the Project Zero community or just keep up with what's happening, visit the Project Zero Web site where you'll find blogs, forums, and a community of fellow developers.
- Refer to
Project Zero
Documentation for all the documents associated with this project, including FAQs,
tutorials, and demos:
- Peruse the Project Zero installation instructions.
- Take a look at an Employee Demo sample PHP application.
- You'll find the Developer's Guide a valuable asset to your Project Zero toolkit.
- Listen to a podcast interview and discussion with IBM Fellow and WebSphere CTO Jerry Cuomo, who provides his insight into Project Zero and its impact on Web 2.0 development.
-
Check out the
developerWorks PHP zone for comprehensive PHP project resources.
-
The
developerWorks Web development zone includes resources for Web developers using Web 2.0 technologies.
-
The
developerWorks Ajax resource center is packed with content and tools to get you starting developing Ajax applications today.
-
The
developerWorks XML zone covers all aspect of developing with XML technologies.
Get products and technologies
- You can find the full instructions for downloading and installing Project Zero for PHP at the Project Zero site.
- Download Eclipse, the platform used in this exercise.
- Download the complete
development environment for PHP within Eclipse.
Discuss
- Participate in the Project Zero discussion forum.






