Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part...

41
Web development with Eclipse Europa, Part 2: PHP development tools How to use Eclipse Europa for Web development using Java technology, PHP, and Ruby Skill Level: Michael Galpin ([email protected]) Developer eBay 11 Dec 2007 No matter what combination of technologies you prefer to work with as a Web developer, Eclipse is a single integrated development environment (IDE) that can increase your productivity. In Part 1 of this three-part "Web development with Eclipse Europa" series, you saw how the latest release of Eclipse — Europa — can be used to develop Java™ Web applications rapidly. Here Part 2, we'll see how easy it is to develop PHP applications using a different set of Eclipse plug-ins, collectively known as the PHP Development Toolkit (PDT). Section 1. Before you start Are you a PHP developer? If so, then what do you use as your development environment? Maybe you're a minimalist who likes to engage in vi vs. Emacs debates. Or maybe you prefer an IDE, but haven't been impressed with the commercial offerings available. Either way, you'll want to take a look at the PHP Development Toolkit for Eclipse. That's right — Eclipse. It's not just for Java developers anymore. A background in PHP programming is essential for getting the most out of this tutorial. Familiarity with the Eclipse IDE is helpful, but not necessary. For some background information about Eclipse, see Resources. About this series In this "Web development with Eclipse Europa" series, you'll see how no matter what PHP development tools © Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 41

Transcript of Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part...

Page 1: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Web development with Eclipse Europa, Part 2:PHP development toolsHow to use Eclipse Europa for Web development using Javatechnology, PHP, and Ruby

Skill Level:

Michael Galpin ([email protected])DevelopereBay

11 Dec 2007

No matter what combination of technologies you prefer to work with as a Webdeveloper, Eclipse is a single integrated development environment (IDE) that canincrease your productivity. In Part 1 of this three-part "Web development with EclipseEuropa" series, you saw how the latest release of Eclipse — Europa — can be usedto develop Java™ Web applications rapidly. Here Part 2, we'll see how easy it is todevelop PHP applications using a different set of Eclipse plug-ins, collectively knownas the PHP Development Toolkit (PDT).

Section 1. Before you start

Are you a PHP developer? If so, then what do you use as your developmentenvironment? Maybe you're a minimalist who likes to engage in vi vs. Emacsdebates. Or maybe you prefer an IDE, but haven't been impressed with thecommercial offerings available. Either way, you'll want to take a look at the PHPDevelopment Toolkit for Eclipse. That's right — Eclipse. It's not just for Javadevelopers anymore. A background in PHP programming is essential for getting themost out of this tutorial. Familiarity with the Eclipse IDE is helpful, but not necessary.For some background information about Eclipse, see Resources.

About this series

In this "Web development with Eclipse Europa" series, you'll see how no matter what

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 41

Page 2: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

your language of choice is, Eclipse is the platform for Web development. Its flexibleplug-in system makes it easy to create versions of Eclipse customized for Webdevelopment with Java technology, PHP, and Ruby. You'll see how different plug-insgive Eclipse unique capabilities for each language. You'll also see some of thecommon features that all Web developers can take advantage of. Throughout thisseries, we will be creating a sample baseball Web application, which will allow us toenter in game data for baseball players and calculate statistics for those players.

About this tutorial

Eclipse has been a favorite IDE for Java developers for many years. However,Eclipse was designed to be a development platform for any language. Eclipse iswritten in the Java programming language, so, naturally, Java development was anobvious starting point for it. Eclipse's plug-in architecture has led to a bounty ofpowerful plug-ins and has been key in the success of Eclipse. Taking these two factstogether — Eclipse's strength as a development platform for any language andEclipse's plug-in architecture — and you have the ingredients for an Eclipse-basedIDE for PHP. That's exactly what has happened with the development of the PHPDevelopment Toolkit.

This is Part 2 of a three-part tutorial series on developing Web applications withEclipse. So far, we've seen how easy it is to develop Web applications in the Javalanguage using the Eclipse IDE for Java EE Developers. The Java EE edition isreally just a collection of plug-ins running on the Eclipse Platform. In this tutorial,we'll see how to develop PHP applications using a different set of Eclipse plug-ins,collectively known as the PHP Development Toolkit (PDT). We'll also see a repriseof some features in the Java EE Edition that are also part of the PDT.

Prerequisites

A background in Java programming is essential for getting the most out of thistutorial. Familiarity with the Eclipse IDE is helpful, but not necessary.

System requirements

You'll need the following installed on your computer:

Eclipse EuropaThis tutorial uses Eclipse V3.3 (Europa).

Java Development Kit (JDK)This tutorial shows you how to develop Web applications using Javatechnology, so you'll need the Java Development Kit (JDK) 5.0 or higher.Download V5.0 or V6.0.

Eclipse IDE for Java EE DevelopersYou'll also need the Eclipse IDE for Java EE Developers.

developerWorks® ibm.com/developerWorks

PHP development toolsPage 2 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 3: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Java Runtime Environment (JRE)To run Eclipse, you must have a JRE.

Apache TomcatThe application uses a Apache Tomcat as its container.

MySQL V5.0The application uses MySQL V5.0 as its database.

Java Persistence APIYou will also need the Java Persistence API and, in particular, the OpenJPAimplementation.

Eclipse PHP Development Toolkit (PDT)This tutorial shows you how to develop Web applications using PHP, so you'llneed the PHP Development Toolkit You can get this as a set of plug-ins for anexisting Eclipse installation. If you're new to Eclipse, you can get an all-in-oneinstallation that includes the Eclipse platform and the PDT plug-ins.

PHPYou need PHP, so get the latest version, which at the time of this writing wasV5.2.1.

Apache HTTP ServerYou need a Web server that integrates with PHP. This tutorial was developedusing Apache V2.0.59.

Fancy PHP debuggerYou need a PHP debugger. We used the Zend Debugger V5.2.10.

Operating systemYou need an operating system capable of running all of the above. We usedMac OS X when creating this series, but you can use a modern version ofWindows® or Linux®, as well. Adjust locations of files accordingly.

Section 2. Introducing the PHP Development Toolkit

The PDT hit its 1.0 release in September 2007, so what are you waiting for? Let'sstart using the PDT and becoming more productive PHP developers.

Why an IDE?

Of course, one of the beauties of PHP is that you can accomplish much with verysimple tools. You can write code directly in a "live" directory on your Web server,point your browser to the page, and voilà! Need to change the code? Just modify it

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 41

Page 4: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

with a text editor and refresh your browser. Who needs an IDE?

Applications can start out simple, but inevitably become more complex. The secondlaw of thermodynamics (entropy increases over time) applies as much to softwareengineering as it does to Maxwell's demon (see Resources if you find thesemetaphors are a bit obscure). For most developers, it is much easier to developsuch systems if they have a debugger to stop the execution of code, step throughthe code, examine the state of the application, etc.

Complex applications usually involve multiple developers working on them. Sourcecontrol usually comes into play, and it's nice to have that integrated into yourdevelopment environment. Using source control often involves keeping your sourceand execution environments (Web server, typically) separate. In that case, it's niceto have a development environment that makes it easy to deploy code to your Webserver for you.

PHP development almost always involves working with a database, as well. Ofcourse, you can use command-line and text-based tools for working with adatabase. Or you can use a graphical program to make this easy. It's nice if yourgraphical environment is integrated in to your development environment. There'sthat term: Integrated Development Environment. The PDT is definitely just that.

Why PDT?

Let's assume you're convinced an IDE offers advantages for PHP development. ThePDT is not the first or only IDE for PHP. There are some highly regarded commercialIDEs for PHP. Eclipse PDT is free of charge and is open source. It's built on Eclipse,which means that you get all of the advantages of the Eclipse Platform. It iscross-platform, so you can use it on Windows, Mac OS X, or the Linux distribution ofyour choice. There's a huge ecosystem of plug-ins for Eclipse and, thus, for PDT, soyou can add on specialized functionality as needed, as well as develop in otherlanguages as needed. Let's take a look at just what you get with the PDT.

What do you get?

We've said that the PDT is simply a collection of plug-ins for the Eclipse Platform.Each plug-in provides specific functionality designed to enhance your productivity.The core PHP plug-ins provide syntax highlighting, syntax hints, and integratedlook-up of all PHP core functions. It integrates with your Web server and lets youeasily deploy your code to the Web server. You can view the page in an internalWeb browser or you can designate an external browser (Firefox, Internet Explorer,Safari, etc.) for viewing your pages.

As mentioned, one of the most valuable things you get is an integrated debugger.You can execute your PHP code directly from the PDT (it includes a PHPexecutable) and also debug directly that way. You can also configure your Webserver to use a debug-enabled version of PHP and debug scripts running live onyour Web server.

developerWorks® ibm.com/developerWorks

PHP development toolsPage 4 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 5: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Last but certainly not least, you get non-PHP specific features, thanks to theextensibility of Eclipse. This includes database tools for connecting to any database(any that has a JDBC driver available, which is pretty much all databases,) creatingtables, querying and updating data, etc. There's also a built-in CVS client in the PDT.If you use Subversion instead of CVS, you can easily get a Subversion plug-in touse, instead. Similarly, there's pretty good chance you write JavaScript and CSSalong with PHP; and with PDT, you get a choice of several excellent Eclipse plug-insfor JavaScript and for CSS you can use. Now that you're surely sold on using thePDT for your next PHP project, let's take a look at installing the PDT.

Section 3. Installing the PDT

Getting and setting up the PDT is pretty painless. It's not just built on Eclipse. LikeEclipse, it's completely open source. There are no trial periods or licenses to worryabout. Just download it and go. There are two ways to download it, depending if youalready have Eclipse. If you completed Part 1 of this series, you already have theEclipse Java EE Edition. We'll first look at installing the PDT on top of Eclipse.

Install as a plug-in

We'll start by installing PDT as a plug-in to Eclipse. Eclipse's plug-in architecturemakes this easy. The easiest way to install any Eclipse plug-in is to use its updatesystem. Kick that off by selecting Help > Software Updates > Find and Install, asshown below.

Figure 1. Find and install updates

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 41

Page 6: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Now you want to select Search for new features to install, as shown below.

Figure 2. Search for new features to install

developerWorks® ibm.com/developerWorks

PHP development toolsPage 6 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 7: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Now we need to add the PDT's update site to the list of sites that Eclipse knowsabout. Do that by clicking New Remote Site.

Figure 3. New remote update site

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 41

Page 8: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Now we need to enter the PDT update site's info. For the name of the new remotesite, you can pick whatever you want to help you identify the site ("PHPDevelopment Toolkit Updates," for example). The URL is the important field to enter,and the official site is http://download.eclipse.org/tools/pdt/updates, as shown below.

Figure 4. PHP update site information

developerWorks® ibm.com/developerWorks

PHP development toolsPage 8 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 9: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

The new update site should appear in the list of sites and should be selectedautomatically. Make sure it's the only one selected and click Finish.

Figure 5. Select PHP update site

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 41

Page 10: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Eclipse will now ping the update site for a list of updates available to download andinstall. Select PHP Development Toolkit Updates and click Finish.

Figure 6. Available updates

developerWorks® ibm.com/developerWorks

PHP development toolsPage 10 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 11: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Now you should see the list of features to install and the license agreement. Acceptthe terms and click Finish.

Figure 7. Features and license agreement

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 41

Page 12: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Now Eclipse will download and install the PDT plug-ins. When it's done, it may askyou to restart Eclipse. After that, you should be able to verify the PDT installation byswitching to the PHP Perspective. Select Window > Open Perspective > Other.

Figure 8. Changing perspective

developerWorks® ibm.com/developerWorks

PHP development toolsPage 12 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 13: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

This should bring up a list of available perspectives. Select PHP from the list andclick OK.

Figure 9. Select PHP perspective

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 41

Page 14: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

This should open the PHP perspective. We'll be using that soon, but let's take aquick look at an alternate way to install the PDT.

Install stand-alone

If you're new to Eclipse, there's an even simpler way to install the PDT. You candownload an all-in-one distribution of Eclipse and the PDT. Select and download thePDT All-In-One, then unzip it and launch Eclipse. Once you've launched Eclipse,switch to the PHP perspective by selecting Window > Open Perspective > PHP.

Figure 10. Open PHP perspective

developerWorks® ibm.com/developerWorks

PHP development toolsPage 14 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 15: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Now we should have PDT installed and ready to use. We need to configure EclipsePDT.

Section 4. Configuring the PDT

With the PDT installed, we could start hacking away. There are a couple of morethings we should do first, though. There are a couple of PDT configurations that willmake our development easier. We'll start by configuring our Web server.

Configuring PDT with Apache

We could set up our project and use a directory under our Web server's root as asource folder, but it's better to separate our source and deployment. We need to letthe PDT know where our Web server is so it can publish our source to it. To do this,open your preferences.

Figure 11. Eclipse preferences

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 41

Page 16: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Under Preferences, expand PHP and select PHP Servers.

Figure 12. PHP servers

There's usually a default server already there that hasn't really been configured. Youcould add a new one or just configure the default. Either way, you should see adialog similar to Figure 13.

developerWorks® ibm.com/developerWorks

PHP development toolsPage 16 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 17: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Figure 13. Configure path to Web server

The important thing here is to set the path to your Web server and the URL that willcorrespond to it. Once you have done that, click OK. From the Preferences > PHPmenu, select PHP executables.

Figure 14. PHP executables preference

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 41

Page 18: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Clicking Add should bring up the dialog shown below.

Figure 15. Add PHP executable

You can put whatever label you like. The more important thing is to select thedirectory where your PHP executable lives. You can use the Browse button to findthis if you don't know it off the top of your head. Leave the PHP debugger set to thedefault Zend. Click OK, and you're done configuring your Web server. We're almostdone configuring PDT. All we need to do is configure PDT to talk to our database.

Connecting to MySQL

developerWorks® ibm.com/developerWorks

PHP development toolsPage 18 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 19: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Our application is going to use a database and, in particular, MySQL. The PDT is acollection of plug-ins, and several of those plug-ins provide PHP-specificfunctionality. It also includes several plug-ins for accessing databases. However,accessing a database is not unique to PHP, and, similarly, the Eclipse databaseplug-ins used by the PDT are not unique to the PDT.

If you completed Part 1 of this series, you have already used the database plug-inincluded with PDT. If you completed Part 1 and installed the PDT as a plug-in on topof the Java EE Edition, you've already configured PDT to connect to MySQL. If not,please take a look at Part 1 and create the baseball database described there. Youshould be able to switch over to the Database Development perspective (Window >Open Perspective > Other > Database Development) and use the Data SourceExplorer to connect to the baseball database.

Figure 16. Connecting to the baseball database

Now that we can query our database, we're ready to start writing some more codefor the baseball application we started in Part 1.

Section 5. The baseball application

Now that we've set up the PDT, let's start developing with it. We'll start by creating aPHP project in the PDT. We'll then use the PDT to create our PHP files. We'll use its

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 41

Page 20: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

features to assist with writing the code, then we'll use it to publish the code so wecan test it.

Using the PHP wizards

We'll start by creating a PHP project in the PDT. Make sure you are in the PHPperspective (Window > Open Perspective > PHP.) By default, the PHP Explorerview is in the top-left corner. You can move this around if you like. In the PHPExplorer, right-click and select New > PHP Project.

Figure 17. New PHP project

This will bring up the New PHP Project wizard. It's a simple wizard, in that all youreally need to do is set the name of the project and the location of the code.

Figure 18. New PHP project info

developerWorks® ibm.com/developerWorks

PHP development toolsPage 20 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 21: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Clicking Finish will create the PHP project. Now you can right-click in the PHPExplorer and select New > PHP File.

Figure 19. New PHP file

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 41

Page 22: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

This will bring up the New PHP File Wizard. You can configure the path and thename of the file.

Figure 20. New PHP file info

developerWorks® ibm.com/developerWorks

PHP development toolsPage 22 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 23: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Just click Finish and the PDT will create a new PHP file with a basic skeleton inplace, based on a template you can edit if you like. The first file we'll create is a fileto define constants.

Listing 1. constants.php

<?phpdefine('DB_HOST', "127.0.0.1:3306");define('DB_USER', "root");define('DB_PASSWORD', "password");define('DB_NAME', "baseball");

?>

We've defined database connection constants. Obviously, you'll want to changethese values to correspond to your environment's configuration. One of the nicethings the PDT does is keep track of the structure of our project, including constants.By default, the PHP Project Outline view is in the bottom left corner. Select it,expand the Constants section, and you should see the structure shown below.

Figure 21. PHP project outline view

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 41

Page 24: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Now let's use these constants to create a database connection we can include inany script that needs to access our database. We'll create another PHP file, asshown above. We'll call this one db.php. We'll include our constants file, then we'llneed to create a connection to our MySQL database. If you've written a lot of PHP,you probably know the syntax for this, but if not, PDT can help. By default, the PHPFunction View is also in the bottom-left corner. Select it and look for themysql_connect function.

Figure 22. Using the PHP function view

developerWorks® ibm.com/developerWorks

PHP development toolsPage 24 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 25: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Not only do you get a list of all the standard functions and classes in PHP V5 but youcan access documentation on the function. Just select the function and hover over it.When you have the function you want, double-click it and it will be inserted at yourcursor in the editor. As you start entering the input parameters to the function, theparameter info is displayed above to help you keep track of what you are entering.

Figure 23. Code assist with library function

The mysql_connect function creates a connection to our database. Now we canwrite some code to check that our connection exists. Once again, code assist kicksin.

Figure 24. Code assist suggesting local variables

You can imagine how helpful this kind of code assist becomes, especially as yourproject and scripts become more complicated. The rest of the code for our db.phpscript is shown below.

Listing 2. dp.php script

<?phprequire_once(dirname(__FILE__)."/constants.php");

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 41

Page 26: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);if (!$conn) {

echo "Unable to connect to DB: " . mysql_error();exit;

}

if (!mysql_select_db(DB_NAME)) {echo "Unable to select mydbname: " . mysql_error();exit;

}?>

We'll be able to reuse this script in many places. Let's start by creating a form forentering new players into our system.

Player entry form

Let's create our basic form for entering a new player. We'll create a PHP file callednew_player.php. We'll start off with just the basic HTML.

Listing 3. new_player.php: HTML form only

<html><head>

<title>Player Entry Form</title></head><body>

<form id="entry" method="POST"><input type="hidden" name="action" value="create"/><div id="fnSection">

<span id="firstNameLabel">First Name:</span><input type="text" name="firstName"/>

</div><div id="lnSection">

<span id="lastNameLabel">Last Name:</span><input type="text" name="lastName"/>

</div><div id="submitSection">

<input type="submit" value="Save"/></div>

</form></body>

</html>

The PDT gives you nice syntax highlighting for your HTML. We'll have the formsubmit to itself. So now we just need to add processing logic. We'll use our db.phpscript and once again make use of the PDT's PHP Function view to help us write thedatabase logic. The finished script is shown below.

Listing 4. new_player.php: complete

<?phpif ($_POST["action"]){

$label = "";require_once(dirname(__FILE__)."/db.php");$firstName = mysql_escape_string($_POST["firstName"]);$lastName = mysql_escape_string($_POST["lastName"]);$fullName = "$firstName $lastName";$sql = "insert into Players(First_Name, Last_Name) values

('$firstName','$lastName')";

developerWorks® ibm.com/developerWorks

PHP development toolsPage 26 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 27: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

mysql_query($sql, $conn);$id = mysql_insert_id($conn);$label = " Insert successful for $fullName new ID=$id";

}?><html>

<head><title>Player Entry Form</title>

</head><body><?=$label ?><br/>

<form id="entry" method="POST"><input type="hidden" name="action" value="create"/><div id="fnSection">

<span id="firstNameLabel">First Name:</span><input type="text" name="firstName"/>

</div><div id="lnSection">

<span id="lastNameLabel">Last Name:</span><input type="text" name="lastName"/>

</div><div id="submitSection">

<input type="submit" value="Save"/></div>

</form></body>

</html>

Now we have a full form and script. It's time to test it out.

Deploying to Web server

Deploying to our Web server, Apache in this case, is easy with the PDT. In the PHPExplorer, right-click on the PHP page you want to test and select Run As > PHPWeb Page.

Figure 25. Run as PHP Web page

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 41

Page 28: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

This will bring up the Run PHP Web Page dialog. It lets you know where it is goingto publish your code and what URL it is going to bring up. You can adjust this if youneed to.

Figure 26. Run PHP Web page dialog

developerWorks® ibm.com/developerWorks

PHP development toolsPage 28 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 29: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

By default, Eclipse will use its internal Web browser (this is the "native" browser foryour particular OS, Internet Explorer on Windows, Safari on Mac OS X, etc.) to viewthe Web page. We'll use this setting for now. You should see the page, as shownbelow.

Figure 27. New player page in Eclipse

Enter a new player and click save. This should refresh the page.

Figure 28. Player added page in Eclipse

This is pretty good for quick testing. Chances are, your more complicatedapplications will make heavy use of CSS and JavaScript, so you'll probably wantmore sophisticated debugging options available when viewing your Web pages. Toconfigure the Web browser to use, click Preferences > Web browser, as shown

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 41

Page 30: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

below.

Figure 29. Select Web browser

Now if you relaunch the application, it should be brought up in the browser of yourchoice.

Figure 30. Page launched in Firefox

So far, we've created a simple page and deployed it. Let's continue to explore thePDT's features by building a slightly more complicated page.

developerWorks® ibm.com/developerWorks

PHP development toolsPage 30 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 31: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Section 6. Player management

We next create a list of all players. We'll see a few new ways the PDT can help witha task like this. Let's start by reading all the players from the database.

Displaying all players

The first thing we need to do is show all of our players from the database. We'llcreate a new PHP file called list_players.php. We'll include our db.php script, sincewe'll need to query our database. We'll want to use the PHP functionmysql_fetch_assoc to fetch a row of a data into an associative array in PHP.Let's assume we're not too familiar with this function and need more than the basicdocumentation you get from a hover in PDT. You need the PHP manual, but you'rein luck: Right-click to access the manual, as shown below.

Figure 31. Accessing PHP Manual from PDT

By default, this will open the online manual at PHP.net. You can configure this,which is especially useful if you have a local copy of the manual on your computer.

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 41

Page 32: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

The code for the basic display of players is shown below.

Listing 5. Basic display of all players

<?phprequire_once(dirname(__FILE__)."/db.php");$message = "";$cnt = 0;$sql = "select * from Players";$result = mysql_query($sql,$conn);$list = array();if (!$result) {

$message = "Could not successfully run query ($sql) from DB: " . mysql_error();} else if (mysql_num_rows($result) == 0) {

$message = "No rows found, nothing to print so am exiting";} else {

while ($record = mysql_fetch_assoc($result)){$list[$cnt++] = $record;

}}mysql_free_result($result);

?>

<html><head>

<title>Player List</title></head><body>

<div id="title">Player List</div><div id="pTableBox">

<table border="2"><thead>

<tr><td>ID</td><td>First Name</td><td>Last Name</td>

</tr></thead><tbody>

<?php foreach($list as $player): ?><tr>

<td><?= $player["Id"] ?></td><td><?= $player["First_Name"] ?></td><td><?= $player["Last_Name"] ?></td>

</tr><?php endforeach; ?>

</tbody></table>

</div>

This shows our data, but let's say we want to add some sorting features, as well.

Sorts

Sorting can be done on the database, but we'll do it in PHP just for illustrativepurposes. We'll use a sort for associative arrays.

Listing 6. Associative array sort

<?phpfunction assoc_sort($array, $id="Id", $sort_ascending=true, $is_object_array = false) {

$temp_array = array();while(count($array)>0) {

$lowest_id = 0;

developerWorks® ibm.com/developerWorks

PHP development toolsPage 32 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 33: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

$index=0;foreach ($array as $item) {

if (isset($item[$id])) {if ($array[$lowest_id][$id]) {

if ($item[$id]<$array[$lowest_id][$id]) {$lowest_id = $index;

}}

}$index++;

}$temp_array[] = $array[$lowest_id];

$array = array_merge(array_slice($array, 0,$lowest_id),array_slice($array, $lowest_id+1));

}if ($sort_ascending) {

return $temp_array;} else {

return array_reverse($temp_array);}

}?>

Now we add a way to select a sort and some JavaScript for triggering this on ourWeb page.

Listing 7. Modified player display with sort

<?phprequire_once(dirname(__FILE__)."/db.php");$message = "";$cnt = 0;$sql = "select * from Players";$result = mysql_query($sql,$conn);$list = array();if (!$result) {

$message = "Could not successfully run query ($sql) from DB: " . mysql_error();} else if (mysql_num_rows($result) == 0) {

$message = "No rows found, nothing to print so am exiting";} else {

while ($record = mysql_fetch_assoc($result)){$list[$cnt++] = $record;

}}mysql_free_result($result);$sort = $_GET["sort"];if ($sort){

// sort the datarequire_once(dirname(__FILE__)."/sort.php");$list = assoc_sort($list, $sort, true, false);

}?>

<html><head>

<title>Player List</title><script type="text/javascript">

function doSort(){document.getElementById("sortForm").submit();

}</script>

</head><body>

<div id="title">Player List</div><div id="sort">

<form id="sortForm" method="GET"><span id="sortLabel">Sort by:

<select name="sort" onchange="doSort()"><option value="Id"> </option><option value="First_Name">First Name</option>

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 41

Page 34: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

<option value="Last_Name">Last Name</option></select>

</span></form>

</div><div id="pTableBox">

<table border="2"><thead>

<tr><td>ID</td><td>First Name</td><td>Last Name</td>

</tr></thead><tbody>

<?php foreach($list as $player): ?><tr>

<td><?= $player["Id"] ?></td><td><?= $player["First_Name"] ?></td><td><?= $player["Last_Name"] ?></td>

</tr><?php endforeach; ?>

</tbody></table>

</div>

Now that we've created a more complicated form, we might have more complicatedbugs. It's probably a good time to bring a debugger into the picture.

Section 7. Debugging

To use debugging with PHP, your Web server must be set up to provide debuggingsymbols and to allow a debugger to connect, get debugging information, and controlexecution flow. You must also have a client that can connect to the server. The PDTis just such a client. One of the debuggers it supports is the Zend Debugger. Zend isthe main contributor to PHP in general and a main contributor to PDT, as well.

Installing the Zend debugger

To install the Zend Debugger for PDT, you can use Eclipse's Software Updatefeature. This is just like what we saw with installing PDT as an Eclipse plug-in. Theonly difference is the update site we want is http://downloads.zend.com/pdt.

To install the Zend Debugger on your server, there are a few steps. First, you mustdownload it (see Resources.) Then you need to add it to your PHP extensionsdirectory and configure your php.ini file to enable the extension (and disable anyincompatible extensions.) It comes with a script called dummy.php that provides theactual debugging info to the client. See Resources for a detailed description onconfiguring your server. Once both are in place, we can start debugging inside thePDT.

developerWorks® ibm.com/developerWorks

PHP development toolsPage 34 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 35: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Debugging for PDT

To set a breakpoint in PDT, pick a line in your code, right-click next to it, and selectToggle Breakpoints.

Figure 32. Toggle a breakpoint

To start debugging, right-click on the script in the PHP Explorer and select DebugAs > PHP Web Page.

Figure 33. Debug as PHP Web page

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 41

Page 36: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

You should be prompted to switch to the PHP Debugging perspective. Go aheadand do that. You should see the debugging views, as shown below.

Figure 34. The PHP debugging perspective

developerWorks® ibm.com/developerWorks

PHP development toolsPage 36 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 37: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

You can step through your code now and inspect variables.

Figure 35. Inspecting a local variable

If you use Eclipse for Java development, all of this will look very familiar. It's thesame set of debugging facilities used in Java development. It's a powerful debuggerthat is sure to increase your productivity.

Section 8. Summary

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 41

Page 38: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Eclipse can be used for setting up everything you need for Web development. Itintegrates with databases, Web servers, and whatever else you need. It provideswizards for creating projects and PHP files. It provides syntax highlighting, codeassist, graphical structure views of your code and project, lists of functions, andquick access to documentation. It can easily publish your code and run it. Finally, itbrings Eclipse's powerful debugger to the world of PHP.

In Part 3, we'll use the Ruby Development Tools (RDT) and RadRails plug-ins toextend our baseball application further, taking further advantage of using Europa forWeb development.

developerWorks® ibm.com/developerWorks

PHP development toolsPage 38 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 39: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Downloads

Description Name Size Download method

Part 2 source code os-eclipse-europa2-baseball.zip4KB HTTP

Information about download methods

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 41

Page 40: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Resources

Learn

• Start with "Web development with Eclipse Europa, Part 1: The Java EE forEclipse" if you are new to this series.

• See the Wikipedia entries for the second law of thermodynamics and Maxwell'sdemon, which was a thought experiment meant to raise questions aboutviolating the second law of thermodynamics.

• Find all about the Europa release of Eclipse in the developerWorks article "Awhirlwind tour of Eclipse Europa."

• Get an introduction to Eclipse and a peek at its colorful history in thedeveloperWorks article "Get started with the Eclipse Platform."

• Are you new to PHP? The best place to start is the developerWorks series"Learning PHP."

• Check out all of the PHP resources on developerWorks.

• Increase your PHP productivity even more by learning and using the CakePHPframework in the developerWorks five-part series "Cook up Web sites fast withCakePHP."

• Learn about using DHTML and PHP together in the developerWorks article"Devise Web 2.0 applications with PHP and DHTML."

• PHP integrates easily with native code, such as the Sphinx search engine. Seehow they can be used together in "Build a custom search engine with PHP."

• Documentation, articles, and downloads of Eclipse are available from theEclipse Foundation.

• Interested in what's happening in the Eclipse community? Check outPlanetEclipse.

• Check out the available Eclipse plug-ins at Eclipse Plug-in Central.

• Check out EclipseLive for webinars featuring various Eclipse technologies.

• Check out the "Recommended Eclipse reading list."

• Browse all the Eclipse content on developerWorks.

• New to Eclipse? Read the developerWorks article "Get started with EclipsePlatform" to learn its origin and architecture, and how to extend Eclipse withplug-ins.

• Expand your Eclipse skills by checking out IBM developerWorks' Eclipse projectresources.

• To listen to interesting interviews and discussions for software developers,check out check out developerWorks podcasts.

• For an introduction to the Eclipse platform, see "Getting started with the Eclipse

developerWorks® ibm.com/developerWorks

PHP development toolsPage 40 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.

Page 41: Web development with Eclipse Europa, Part 2: PHP ... · Web development with Eclipse Europa, Part 2: ... In Part 1 of this three-part "Web development with Eclipse Europa" series,

Platform."

• Stay current with developerWorks' Technical events and webcasts.

• Watch and learn about IBM and open source technologies and productfunctions with the no-cost developerWorks On demand demos.

• Check out upcoming conferences, trade shows, webcasts, and other Eventsaround the world that are of interest to IBM open source developers.

• Visit the developerWorks Open source zone for extensive how-to information,tools, and project updates to help you develop with open source technologiesand use them with IBM's products.

Get products and technologies

• Check out the latest Eclipse technology downloads at IBM alphaWorks.

• Download Eclipse Platform and other projects from the Eclipse Foundation.

• Download IBM product evaluation versions, and get your hands on applicationdevelopment tools and middleware products from DB2®, Lotus®, Rational®,Tivoli®, and WebSphere®.

• Innovate your next open source development project with IBM trial software,available for download or on DVD.

Discuss

• The Eclipse Platform newsgroups should be your first stop to discuss questionsregarding Eclipse. (Selecting this will launch your default Usenet news readerapplication and open eclipse.platform.)

• The Eclipse newsgroups has many resources for people interested in using andextending Eclipse.

• Participate in developerWorks blogs and get involved in the developerWorkscommunity.

About the author

Michael GalpinMichael Galpin has been developing Java software professionally since 1998. Hecurrently works for eBay. He holds a degree in mathematics from the CaliforniaInstitute of Technology.

ibm.com/developerWorks developerWorks®

PHP development tools© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 41