Java for PHP Developers

I have been working with Java for android and a Web application purely for entertainment. For long I have seen PHP adopt more and more “ideas” from Java so to make it easy for someone that knows PHP to get into java and vice versa I’ll make some easy generic associations. This is from a HTTP point of view to simplify the relations.

Note: I have some basic background on Java and C# (Mono .NET), also I have an understanding of the design patterns that you will see applied in Java and in PHP frameworks and that helps understand the logic faster between the different languages.

  1. In PHP Controllers are Controllers, in Java they are mostly represented by a Servlet. It’s similar to Symfony 2  and Zend Framework adoption for handling requests. (Also in the Java Servlet can provide routing in the service method but not very used according to the reading I have been doing and the web.xml handles more of those requests).
  2. In PHP Models are provided by Frameworks Zend Framework or Symfony also has them, in Java they are usually called Beans and they also take the role of “Services” witch is something that came up in Zend Framework 2 and Symfony 2 not knew but the concept in the framework has been more noticeable.
  3. Template in PHP is done using some one of the following (known to have more) Smarty, Twig, normal PHP + HTML. In Java it is done via “tags” in Javaserver Pages (JSP) the approach of Javaserver Pages + Tags + Controller (Servlet) looked a lot like the Symfony 2 approach. (or vice versa)
  4. HTTP Server Jetty (there is jetty for android) is a simple to use webserver built in java witch is simple to deploy and run you can print a hello world pretty fast with not much work with it. Apache/Nginx install + PHP + some DB still is faster to me since it actually has more documentation and isn’t so java centered.
  5. Build and dependency management tools Maven is a most simple way to manage and install dependency’s in Java just get some example pom.xml files to get your basics and understand the build process and it looks like composer (yes that thing that many criticize). Maven also can create standard working environments and run tests.
  6. A ORM known in PHP is Doctrine a similar ORM in Java can be Hibernate. Hibernate also supports config by Annotations.
  7. Configuration in PHP can be handled on whatever you want to use, in frameworks like Symfony 2 it’s known has app/config.yml in Zend Framework 1 it’s application.ini in Zend Framework 2 it’s TODO something it’s more of a users choice. Symfony 2 also supports Annotations (via Doctrine Annotations) for route config et all, but in Java the Spring Framework his what I know to have those quirks but the Annotations are built in the language the main configuration for web development is usually a web.xml file in a WEB-INF directory.
  8. Database connetions PDO is for PHP what JDBC is for Java for database connection
  9. Packaging WAR or JAR it’s Java package what was based for Phar files in PHP
  10. Unit testing in PHP can be PHPUnit and in Java it can be jUnit
  11. Routing requests If you are looking in a more annotation style configuration for routing requests look at this text from wikipedia JAX-RS: Java API for RESTful Web Services and Rewrite Engine

This is a somewhat generic way of comparing the two languages but what you can notice is that Java like PHP has some built around solutions built with the language but they are supplied by standard API has .jar files and like PHP it also has a very intense activity around and different solutions ( just to say maybe we shouldn’t criticize having a lot of frameworks as Matthew Weier O’Phinney says:

Second, I also think there’s space for multiple implementations of any given component. Often there are different approaches that different authors will take: one might focus on performance, another on having multiple adapters for providing different capabilities, etc. Sometimes having a different background will present different problem areas you want to resolve. As such, having multiple implementations can be a very good thing; developers can look at what each provides, and determine which solves the particular issues presented in the current project.

(this last quote was placed because of a lot of discussion I see in forums and mailing lists regarding standardization of the way the developer codes and the way the language is built. Nothing new was said but the discussion of the PHP group (fig) is “deja vu”.

Coding in Java…

Well it’s not that simple has in PHP… Small example you do a POST in PHP you could just $_POST[“FormDemo”][“id”] , $_POST[“FormDemo”][“name”] , in Java it follows the standards strictly and you can only handle key value pair posts. You can handle the PHP POST array format but that involves regular expressions for what I’ve seen not simple has in PHP.

In Java you get strings via HTTP and change it to the format you require, in PHP you get Strings or whatever and you rarely care and if you care much you can type cast the variable if it’s int, float or Array.

Integer.ParseInt(string) will be your friend for Integer values for the “what you may want”.

Map<String,String> KeyValue = new Map<String,String>();

Build setup:

I started by using Eclipse + Eclipse Web development tools and jetty with basic code, then installed Maven and plugin search for it in eclipse market I wasn’t thinking on hibernate but I wanted something more abstract to handle the database and I am using Doctrine in PHP so just searched for a ORM in Java and went with that one.



PHP is simpler to use my issue with Java it’s not about the Type declaration I actually like that and sometimes wish that was better in PHP. I actually didn’t like the server setup requirements I started with jetty witch is very simple but the deployment using maven and all that… If I was coding pure PHP it would have been faster and simpler. Frameworks in Java allow you the basic to build “normal stuff” in a simpler way like “routes” et all. But in PHP you actually can get something like that in a more simpler way and faster by just coding. JavaEE at the just looks like over complicated for a simple web app solution.

Zend Framework Zend Db Profiler

Analyzing database SQL query’s within Zend Framework Front Controllers isn’t difficult here’s an example:

$bootstrap = $this->getFrontController()->getParam(“bootstrap”);

if ($bootstrap->hasPluginResource(“db”)) {
      $dbResource = $bootstrap->getPluginResource(“db”);
      $db = $dbResource->getDbAdapter();

$profiler = $db->getProfiler();

            foreach ($devs->getDevices($cliente->idcliente) as $equip) {

                $equip->findDependentRowset(“DM_Model_Services”, “equipment”);
    $query = $profiler->getLastQueryProfile();

    echo $query->getQuery();      


My database config in application.ini:

resources.db.adapter         = pdo_mysql     =
resources.db.params.username = user
resources.db.params.password = pass
resources.db.params.dbname   = sal_db

This will give an output like:

SELECT `service`.* FROM `service` WHERE (`idequipment` = 70)



Primeira colocação do uso de selenium no meu projecto de trabalho.

16:52:56.775 INFO – Started org.openqa.jetty.jetty.servlet.ServletHandler@7ad81784
16:52:56.775 INFO – Started HttpContext[/wd,/wd]
16:52:56.779 INFO – Started SocketListener on
16:52:56.779 INFO – Started org.openqa.jetty.jetty.Server@6f507fb2
16:54:27.227 INFO – Checking Resource aliases
16:54:27.245 INFO – Command request: getNewBrowserSession[*chrome, http://cableweb/%5D on session null
16:54:27.257 INFO – creating new remote session
16:54:27.430 WARN – Caution: ‘/usr/bin/firefox’: file is a script file, not a real executable.  The browser environment is no longer fully under RC control
16:54:27.432 INFO – Allocated session ad8fbaba3c6a4caba2aaa62f118253b8 for http://cableweb/, launching…
16:54:27.516 INFO – Preparing Firefox profile…
16:54:32.489 INFO – Launching Firefox…
16:54:35.965 INFO – Got result: OK,ad8fbaba3c6a4caba2aaa62f118253b8 on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.028 INFO – Command request: setTimeout[30000, ] on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.052 INFO – Got result: OK on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.104 INFO – Command request: open[/index.php, ] on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.356 INFO – Got result: OK on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.407 INFO – Command request: click[link=Aquisições, ] on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.426 INFO – Got result: ERROR: Element link=Aquisições not found on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.477 INFO – Command request: testComplete[, ] on session ad8fbaba3c6a4caba2aaa62f118253b8
16:54:36.477 INFO – Killing Firefox…
16:54:36.513 INFO – Got result: OK on session ad8fbaba3c6a4caba2aaa62f118253b8
16:55:30.999 INFO – Command request: getNewBrowserSession[*chrome, http://cableweb/%5D on session null
16:55:30.999 INFO – creating new remote session
16:55:31.000 INFO – Allocated session 38cbb4859dcf4cdfb8c33f7f160c56f7 for http://cableweb/, launching…
16:55:31.060 INFO – Preparing Firefox profile…
16:55:33.334 INFO – Launching Firefox…
16:55:35.379 INFO – Got result: OK,38cbb4859dcf4cdfb8c33f7f160c56f7 on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.427 INFO – Command request: setTimeout[30000, ] on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.438 INFO – Got result: OK on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.490 INFO – Command request: open[/index.php, ] on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.691 INFO – Got result: OK on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.742 INFO – Command request: click[link=Aquisições, ] on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.759 INFO – Got result: ERROR: Element link=Aquisições not found on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.810 INFO – Command request: testComplete[, ] on session 38cbb4859dcf4cdfb8c33f7f160c56f7
16:55:35.811 INFO – Killing Firefox…

Houston we have a #FAIL

Apesar do fail isto é apenas o principio, os testes ficaram relativamente bem feitos com o selenium IDE, agora em codigo tenho de resolver situações, que não consigo cobrir com o selenium IDE.

Controlo de uso de CPU em perl

Fica aqui o codigo que escrevi simples mas modular o suficiente para ser replicado por mais pessoas.


Desculpem a mistura de Inglês com o Português.

# Verificar o tempo de idle do cpu e agir de acordo
# @version $Id: 5432 2011-05-05

# Permitir um tempo maximo de idle de x segundos
# Definir o tempo permitido em idle por esta var
our $processcount_cpuallowidletime = 120;
# Maximo de tempo que o processo ira ficar com controlo de idle time
our $processcount_cpuallowtotalidletime = 500;

# dormir durante x tempo porque o processo esteve sem fazer nada
our $process_sleeptime = 2;

# Guardar dados sobre idle process count
# Estrutura de dados para indicar o tempo de idletime
our %idletime = (
start => 0,
end => 0,
total => 0,

# $processcount pertence ao ficheiro "main" e nao deve ser definido aqui
# esta var indica se o processo esta a fazer algo se > 0

=item checkidle

Called function to validate idle time


sub checkidle {
if ($DEBUG > 0 ) {
syslog("debug", "inicio Verificar idle time pcount=".$processcount." t=".$idletime{'total'}." allow=".$processcount_cpuallowidletime." pslp=".$process_sleeptime);

if ($processcount == 0 ) {

if ( $idletime{'start'} == 0 ) {
$idletime{'start'} = time();

$idletime{'end'} = time();

$idletime{'total'} = $idletime{'end'} - $idletime{'start'};


if ($idletime{'total'} > $processcount_cpuallowidletime ) {
$process_sleeptime = $process_sleeptime*2; # recalculate value of sleep time
if ($DEBUG > 0 ) {
syslog("debug", "A dormir durante ".$process_sleeptime." seconds...");
syslog("info", "Sleeping:".$process_sleeptime);

if ( ($processcount > 0 || $idletime{'total'} > $processcount_cpuallowtotalidletime) && $idletime{'start'} != 0 ) {

if ( $DEBUG > 0 ) {
syslog("debug", "fim Verificar idle time ".$processcount." ".$idletime{'total'}." ".$processcount_cpuallowidletime);

if ($process_sleeptime > $processcount_cpuallowtotalidletime ) {
$process_sleeptime = 1;

=item resetIdleTime()

Reset idle time counters


sub resetIdleTime {
$idletime{'start'} = 0;
$idletime{'end'} = 0;
$idletime{'total'} = 0;


Virus inteligente no MSN

*** No msn vindo de uma amiga da minha esposa… ***

raquel diz (20:58):
Hi are you there?
raquel diz (21:31):
Hi are you there?
raquel diz (22:36):
Hi are you there?
minha esposa diz (22:49):
Tens virus no pc …
Ou começaste a falar Inglês assim de repente ?
raquel diz (22:49):
lol no its me
minha esposa diz (22:50):
és mesmo tu ? Podes falar português só para confirmar é que costumas ter virus no pc…
raquel diz (22:50):
I just took an IQ quiz
minha esposa diz (22:50):
É o EU mas a minha esposa está aqui ao lado
raquel diz (22:50):
I was smarter than I am! I scored 111

Ainda por cima o vírus diz que está mais inteligente… Realmente um vírus a usar o msn(messenger) de alguém comprova a sua inteligência.

PHP Unit testing

Desenvolver a aplicação dá trabalho e desenvolver testes aumenta esse trabalho e tempo de desenvolvimento. Mas pode ser muito proveitoso a longo prazo.
Exemplo disto é ter criado vários componentes de uma aplicação e para testar todo o seu funcionamento e resultado correcto de processos usei o phpunit ou até scripts simples de testes.
O PHPUnit permite uma melhor padronização de todos os testes e depois até agrupa-los a uma ferramenta como o phpUnderControl.
Em grandes processos e num ambiente de rápida alteração dos mesmos devido a mudanças de lógica de negócio isto pode ser uma mais valia.
Ou até mesmo para testar a aplicação antes de colocar a mesma em produção pode poupar muito tempo em debuging.

Existem linhas de código de exemplo no site do phpunit para dar um auxilio inicial não acho isto complicado, desde que tenhamos uma noção do que vamos testar e como preparar os dados para esse teste. Tive de usar uma BD de testes padrão e usar o setUp() e tearDown() do phpunit para trabalhar a BD antes do inicio dos testes de modo a que a BD contivesse dados preparados para testar o processo alvo.

Este texto é para encorajar as pessoas a criarem testes unitários para evitarem futuros problemas em grandes processos.

PDT Eclipse Get e Set Template

Window -> Preferences -> PHP -> Editor -> Templates -> New

Name: sg
Description: qualquercoisa
context: php
Automatically insert: checked

Para activar escreve sg«e carrega CTRL + espaço (Space) »

* Set the variable ${variable}
* @var string $$${variable}
* @return ${class_container};
public function set${variable}($$${variable})
$$this->${variable} = $$${variable};
return $$this;
* Get the variable ${variable}
* @return String
public function get${variable}()
return $$this->${variable};

UPDATED to match my current config.