Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Java application & PHP

Tags:

java

php

api

I have a java program that has a healthy Java API, but I want build a primitive interface between my java application and a php script as those are the requirements of my project.

My first attempt was to write a PHP script that ran an passthru function to run the jar. i.e.

passthru("java -jar myjarfile param1 param2 param3")

This worked but proved to be quite slow because the jar file had to be launched and executed etc.

My next attempt was to create a servlet on Tomcat7 and interface it with PHP by usin the curl() command. i.e.

curl(http://myserver/mywebapp/myservlet?p1=param1&p2=param2&p3=param3);

This had excellent performance , but the servlet was very unstable and crashed after about 5 minutes (i was loading the server with about 1 request every 10 seconds)

I come to Stack Overflow asking: am i doing this right? Is there a better way? How can I have my java program running in a jvm and interact with it using PHP?

Thanks

like image 503
Tucker Avatar asked Oct 10 '22 08:10

Tucker


2 Answers

There is a world of difference between the Java method of handling things and the PHP method of handling things.

PHP basically runs every script from beginning to end for each request, which amounts to a very imperative programming technique. Java, on the other hand, typically handles stuff by modules that remain in memory for many more than one request. To integrate the two, you need to consider more than the "function calls", you need to consider how those two environments can be meshed cleanly.

Launching the java per PHP request is asking Java to behave like PHP. In other words, you are going to discard most of the best reasons to use Java by making it work like PHP. Instead, consider setting up a Tomcat (or something similar) instance and passing a request from one to the other. In other words, have the PHP make a web request to a Java environment, which handles things without complete buildup and teardown of the Java interpreter (which is how PHP handles things).

like image 167
Edwin Buck Avatar answered Oct 13 '22 11:10

Edwin Buck


I'm assuming that because you attempted to use a JAR you can have the PHP and Java on the same machine. You may find this document on Java integration in PHP quite exciting. Note that I have never used it, I only know it exists. Be sure to read the introduction.

like image 21
Levi Morrison Avatar answered Oct 13 '22 11:10

Levi Morrison