Wednesday, January 21, 2009

PHP and Java Collections: More PHP, Less Java

We've added some nice integration with the Java collection classes in Zero.

Java has a rich set of collection classes. The three really important ones are Set, Map and List. We use the Java collections quite a bit when integrating Java libraries in PHP applications. So it got us thinking whether we could provide some good PHP syntax for these classes. It turns out there are quite a few things we could do to improve working with these classes in PHP.

For example, Java lists now support the following:

<?php
java_import("java.util.ArrayList");
$list = new ArrayList();
$list->add("Hello World!");

$list[0] = "Hello Again!"; 
$value = $list[0]; 
$array = (array) $list;
$check = isset($list[0]);
unset($list[0]);

// Append some items to list
$list[] = "Hello Again!";
$list[] = TRUE;
$list[] = "Updated!";
?>

Java maps and sets also get the full treatment. The reason why I like this is that it avoids lots of Java API calls. Some example code for hacking around with a Map using the Java APIs is shown below. Notice all the method calls, just so much more long winded than PHP's nice expressive syntax!

<?php
$map = new Java("java.util.HashMap");
$map->put("title", "Java Bridge!");
$value = $map->get("title");
$check = $map->containsKey("title");
$map->remove("stuff");
?>

More information is on the Project Zero PHP/Java Bridge reference page here.

Creative Commons picture attribute to MicMac.

2 comments:

  1. This is where it starts getting tricky. There is stuff like this emerging in PHP's SPL too:
    http://www.colder.ch/news/01-16-2008/30/new-datastructures-in-spl.html

    I guess many Java dev's coming to PHP via ProjectZero will tend to prefer their "good old" stuff over whatever PHP has to offer. Lrt alone migrate their code to what ever PHP adds later on. Then again it totally makes sense to make it possible to leverage existing Java libs since its so trivial for you guys.

    ReplyDelete
  2. Hi Lukas, yes that's very interesting - Zero doesn't currently support all of SPL but it is something we are working towards. This does create new interop scenarios.

    For example, a PHP script could create an SplDoublyLinkedList and call a Java method that expects a Java List. It would be very nice to do the conversion automatically. It need not necessarily involve copying the data into a Java list either because we might be able to implement a Java list on top of the underlying PHP SplDoublyLinkedList.

    ReplyDelete