JavaUsing PHP and Java in the Same App with PHP/Java Bridge

Using PHP and Java in the Same App with PHP/Java Bridge

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

As you probably know, PHP 4 supported an extension for combining PHP with Java, but to combine PHP with Java in PHP 5 or PHP 6 you should install the PHP/Java Bridge, which the website describes as:

“… an implementation of a streaming, XML-based network protocol, which can be used to connect a native script engine, for example PHP, Scheme or Python, with a Java virtual machine.”

In this article you will learn how to install and configure the PHP/Java Bridge and how to use Java classes in PHP scripts in a demo application. To use the PHP/Java bridge, you should have knowledge of Java SE and the PHP5 core, as well as how they interact.

Using the PHP/Java Bridge

The current distribution of the PHP/Java Bridge is available for download as a .zip file from the project page. The installation process depends on which Java platform will be interacting with PHP through this bridge. For J2SE, installation is simple:

  1. Install J2SE 1.6 or above.
  2. Install PHP 5.1.4 or above.
  3. Extract the php-java-bridge_5.2.2_j2ee.zip to a folder.
  4. From the command prompt, navigate to this folder and type: …>java –classpath JavaBridge.war TestInstallation
  5. In the current folder, you should see an ext folder that contains four .jar files. Copy JavaBridge.jar and php-script.jar to your J2SE/Java SE ext directory ({JAVA_HOME}/jre/lib/ext).

Here’s how to install the PHP/Java Bridge for J2EE:

 

  1. Copy JavaBridge.war archive into the auto-deploy folder of your J2EE server or servlet engine (Tomcat, Resin, etc.).
  2. Rename this .war archive whatever you’re calling the new application and restart the J2EE server. Wait for the auto-deploying process to create the directory associated to this .war. In this example, the app is called appName.war.
  3. Test the new application from the browser like this: http://localhost:8080/appName (click on test.php).
  4. If you have your J2EE server running on a different host or listening on a different port, then modify these parameters accordingly.

Before implementing the application, you must know that the PHP/Java Bridge comes with a set of functions (PHP classes) that were especially created to integrate Java code into PHP scripts. Some of these functions are:

  • java: This allows you to access the Java type with the given name. For example:
    java("java.lang.System")->getProperties();
  • java_autoload: This allows you to load a set of Java libraries in the current PHP script. For example:
    java_autoload("my_1.jar;my_2.jar");
  • java_cast: This allows you to convert a Java object into a PHP value. For example:
    $mystr=new java("java.lang.String","9");$phpnr=java_cast($mystr,"integer");echo $ phpnr;
  • java_is_null: This allows you to check if a value is null or not. For example:
    java_is_null(java("java.lang.System")->;getProperty("my_prop"))
  • java_session: This allows you to return a session handle. For example:
    $session = java_session();
  • java_values: This allows you to evaluate the object and fetch its content (only if this is possible). For example:
    $result = java_values($calcinstance->addAB($term_1,$term_2));

To use these functions, your PHP applications must contain the corresponding PHP classes. The most important class is Java.inc, but the complete list of classes can be seen in the appName/java directory.

The PHP/Java Demo Application

Now that you have learned some basic information about the PHP/Java Bridge, we can start developing our first PHP/Java application: a florist shopping cart app that displays six bouquets of flowers and their corresponding prices. The application is a PHP script that implements a Java session bean, which will be the “engine” of the application because the results will be provided by a Java class named flowerBean. In other words, Java behaves as a pure business logic component and PHP behaves as an interrogator component. Essentially, PHP will pass the flower item to dedicated Java methods and will receive the flowers images and their corresponding prices, displaying them to the user. Users can add or remove items from their shopping carts.

The PHP script interacts with FlowerBean.java (listed below) through its set– and get-specific methods. The results are shown in the figures at the end of the article.

Listing FlowerBean.java

package com.beans.flowers;
import java.io.Serializable;
import java.util.Vector;

public class FlowerBean implements Serializable {

private String[] flowers = new String[]{"flower1.jpg", "flower2.jpg",
"flower3.jpg", "flower4.jpg", "flower5.jpg", "flower6.jpg"};
private int price;
private Vector shopcart = new Vector();

public String[] getFlowers() {
return flowers;
}

public int getPrice(String flower) {
if (flower.equals("flower1.jpg")) {
return 130;
}
if (flower.equals("flower2.jpg")) {
return 230;
}
if (flower.equals("flower3.jpg")) {
return 123;
}
if (flower.equals("flower4.jpg")) {
return 111;
}
if (flower.equals("flower5.jpg")) {
return 250;
}
if (flower.equals("flower6.jpg")) {
return 110;
}
return 0;
}

public Object[] getShopcart() {
if (shopcart != null) {
if (!shopcart.isEmpty()) {
return shopcart.toArray();
}
}
return new String[]{};
}

public void addToShopcart(String item) {
shopcart.add(item);
}

public void remToShopcart(String item) {
if (shopcart != null) {
if (shopcart.contains(item)) {
shopcart.remove(item);
}
}
}
public void emptyShopcart() {
if (shopcart != null) {
shopcart.removeAll(shopcart);
}
}
}

After you compile this Java source, place it in a .jar archive named flowerBean.jar. Copy this file to the products/WEB-INF/lib directory.

Now it’s time to develop the PHP script that will call the above Java class. Using the methods described in the “Using the PHP/Java Bridge” section, you can write the productlist.php, listed below:

Listing productlist.php

<?php require_once("java/Java.inc");

$session = java_session();

if(java_is_null($t=$session->get("bean"))) {
$session->put("bean", $t=new Java("com.beans.flowers.FlowerBean"));
}

if(isset($_GET['addfloweritem'])){
$t->addToShopcart($_GET['addfloweritem']);
}
if(isset($_GET['remfloweritem'])){
$t->remToShopcart($_GET['remfloweritem']);
}
if(isset($_GET['emptyitems'])){
$t->emptyShopcart();
}

unset($_GET['addfloweritem']);
unset($_GET['remfloweritem']);
unset($_GET['emptyitems']);

?>

<html>
<head>
<title>Best Flower Shop</title>
<style>
.flStyle5 {
font-family: Helvetica,Arial,sans-serif;
color: #00000;
font-size: 24;
font-weight: bold;
}
.flStyle6 {
font-family: Helvetica,Arial,sans-serif;
color: #00000;
font-size: 20;
font-weight: bold;
}

</style>
</head>
<body>

<?php $flowers = java_values($t->getFlowers()); ?>
<table align="center">
<tr>
<td colspan="<?php echo(sizeof($flowers)); ?>" align="center"
class='flStyle5'>BEAUTIFUL FLOWERS IN THE CITY</td>
</tr>
<tr>
<?php
foreach ($flowers as &$value) {
echo("<td><img src='images/".$value."' alt=''></td>");
}
?>
</tr>
<tr>
<?php
foreach ($flowers as &$value) {
echo("<form name='shopForm_".$value."' action='".$PHP_SELF.
"' method='get'>");
echo("<input type='hidden' name='addfloweritem'
value='".$value."'>");
echo("<td align='center'>Buy me! $".java_values($t->
getPrice($value))." <input type='submit' value='Buy'></td>");
echo("</form>");
}
?>
</tr>

</table>
<br><br>

<?php $items = java_values($t->getShopcart()); ?>
<table align="center">
<tr>
<td align="center" colspan="2" class='flStyle6'>YOUR SHOPPING CART</td>
</tr>
<?php
echo("<tr>");
if(sizeof($items)==0) {
echo("<td colspan='2' align='center'><b>Empty cart!</b>
<img src='images/1.gif' alt='' width='20' height='20'>
</td>");
echo("</tr>");
} else {
echo("<td colspan='2' align='center'><b>Nice choice!</b>
<img src='images/2.gif' alt='' width='20' height='20'>
</td>");
echo("</tr>");
foreach ($items as &$value) {
echo("<tr>");
echo("<td>");
echo("<img src='images/".$value."' alt='' width='60'
height='60'><b>$".
java_values($t->getPrice($value))."</b>");
echo("</td>");
echo("<td>");
echo("<form name='remForm_".$value."' action='".$PHP_SELF."'
method='get'>");
echo("<input type='hidden' name='remfloweritem' value=
'".$value."'>");
echo("<input type='submit' value='Do not buy!'>");
echo("</form>");
echo("</td>");
echo("</tr>");
}
echo("<tr>");
echo("<td>");
echo("<form name='emptyForm' action='".$PHP_SELF."' method=
'get'>");
echo("<input type='hidden' name='emptyitems' value='empty'>");
echo("<input type='submit' value='Empty Shopcart'>");
echo("</form>");
echo("</td>");
echo("</tr>");
}
?>

</table>

</body>
</html>

 

The PHP/Java App in Action

You can see the output of mixing PHP with Java in this application by browsing to localhost:8085/products/productclist.php. Figures 1-3 show screenshots of user interactions with the completed shopping cart application.

Figure 1 shows the default shopping cart. The items are listed using the PHP script that calls the flowerBean class.

PHP and Java -- Default Shopping Cart

Figure 2 shows a user buying some of the bouquets using each corresponding Buy button. The shopping cart lists them in the same page using the PHP script that calls the flowerBean class.

PHP and Java -- User Buying Bouquets from Shopping Cart

Figure 3 shows a user removing an item from the shopping list, after which the shopping cart shows the new listing of items.

PHP and Java -- Removing an Item from the Shopping Cart

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories