From PHP to Java

So I’m a Java developer for some time now and I’d like to share with you few things about the process I went through. I want to point few differences in the process, libraries and way of working between the languages.

A bit of background

I’m a senior developer and I was writing Java for some time already before I switched. Usually side projects but not that small. Turns out, as I was already writing quite complicated code structures in PHP 5.6/7 there was no big change when compared PHP to Java.

Another nice surprise was Symfony and Doctrine to be PHP clones of Spring and Hibernate. Knowing both frameworks helped me a lot with catching up with RAD in Java.

To be hones a lot of currently hyped tools for PHP (not Laravel) are based on Java tools. Just like composer being replacement for Maven/Gradle.

So what’s the difference?

First is deepness of the language. There is way more than associative array. Java, for each collection, has multiple implementations with different characteristics so you need to learn what is what.

OO model has also way more to offer. At the beginning you can play with PHP style of composing classes but when you have enum as first class citizen of the language you just want to use it :) Inner classes, static classes and I haven’t event started talking about streams or generics. On top of that there is concurrency, parallelism and need, or lack of need, of being thread safe.

A lot of stuff and I’m still discovering new keywords of the language from time to time.

Is it that bad?

Not really. Writing PHP in Java is very easy. It works a bit worse the other way around. Simple Spring apps are easy and fast to write. As I landed in the team of experienced developers it took me few weeks to learn what I was missing and is used in day to day work.

I think the biggest change for me was move from Composer to Maven. As PHP don’t require a lot of build features Composer is nice and simple. Maven on the other hand is a 20 years old monster with XML configuration. It’s not bad but it takes a while to get used to. After some time and few mistakes it’s pretty straight forward in use and there is a lot of tutorials.

Documentation

At the beginning of every journey into new language you’ll follow the Stack Overflow Driven Development methodology. And it’s working very well in Java as it’s one of the most popular languages in the world. 99.9% questions you may ask will be answered there.

When it comes to libraries it’s more hit and miss. Sometimes documentation is amazing and you can use it to basically copy/paste base solutions. Otherwise you end with digging through big manuals written in very corporate way and without many examples. From time to time you’ll probably end up reading the code as well. In my opinion tho, it’s the best solution anyway. I learn a lot faster by reading other people code than by reading dry manuals or books.

Tooling

As I mentioned before, Maven and Gradle are monsters of build. You need them as it’s not only about FTP files to the server ;) You need to compile your code and run it as binary package. Learning curve is steep but in few weeks of daily tasks you’ll learn a lot. Or at least enough to know where to look for template for new project.

IDE is great help. As you have a lot to choose from for free, like Eclipse of Netbeans, I say inteliJ from JetBrains is simply the best. Community Edition let you work on Java for free as well but without some features. I own my own licence for Ultimate version and it’s the best £20 I’m spending a month. Especially as a polyglot, where I’m using quite few languages supported by it.

What next?

Kotlin! You probably heard about it when Google made it one of officially supported languages for Android. It will soon be supported fully in Spring. With full interop with Java and more Scala-like markup it’s amazing tool to code. And it’s fun.

JVM has also Groovy, Clojure, Scala and a lot of other languages to play with. They will let you learn more about coding and still use your new favourite platform.

Summary

It’s more a journey than travelling from place to place. As I learned quite few things about language and libraries there is still a lot to do. Stay tuned. I’ll post another part in few moths on the next iteration of my learnings.

Event driven microservices

I’ve got lucky I got my spot in last London GOTO conference. Theme was obviously event driven microservices and how they simplify whole architecture of complex applications. After 2 days of listening about them there was no other choice than prototype.

Most intriguing for me was the idea of performing read through event bus as well as writes. It kinda hit me as being against CQS. Couldn’t get why and how. Being in mindset of transactional storage wasn’t helping as well :P

Building event driven microservices

Requirement as simple. One service is providing data and other is requesting and processing it. And some interface to interact with. No need for web, as it’s prototype/proof of concept. Console app it is and Symofny as framework of choice as the simplest way to scaffold code. Yesterday I was thinking about getting kafka but again, I wanted to see results not caring much about technology.

If you want to do system like that in real life please don’t use PHP for that :D

Code you will find here.

So how it works?

I’ve got positively surprised by the effect. Everything was obviously done under a second. Even checking on microsecond level shown loads of time saved in comparison to HTTP.

Think this way – sending order and getting item gives you 2 HTTP calls. It’s not much but with more services interested in this topic it will only grow. And all of it will be done during main order request. So user facing system will be slowed down by every new service attached. Even if response time is about 50ms with only 4 of them it adds 200ms on top of all other processing.

When your microservices communicates with each other with events you’re getting at least three advantages I can think of right now:

  1. No HTTP, less network connections means less time wasted on the wire
  2. Events are asynchronous so if your critical path is finished you can inform end user about it without waiting for all the rest to finish
  3. If one of services in chain fails events will stay in the infrastructure. You’re not loosing any data.  Rest of system is working as normal. Error is atomic to one place. And after it’s fixed you can start processing messages from where it stopped.

Last point is illustrated in my example. When you request non existent item ItemService will fail. Fix collection adding new index and rerun it. Boom. Order gets processed like nothing happened. Just with a bit of delay.

Conclusion

If you can use this pattern it will give you a lot of freedom. Communicating with event bus of any sort will save you a lot of time and money. One thing to do is just to convince your team and company it’s the right thing to do. But it’s topic for another post ;)

From PHP to Java #1 – First production-ish application

So I’ve got a task to check difference in performance between Silex app, Symfony 3 with all goodies and JAVA/Spring Boot. Results surprised even me.

TLDR; because there will be separate post about that – PHP is obviously slower than Java and with proper use of opcache there is no difference between Symfony 3 with JMS Serializer and Doctrine and 60 lines unmaintainable app in Silex.

But it should be about Java. Stack Driven Development with Spring Boot took me maybe 1 or 2 hours in comparison about 1h with Symfony. As I’m still newbie I’m not optimising what so eves as I have just slight idea what I’m doing. App is working exactly the same way. Let’s do testing then.

Environment

I’m having all the apps on my poor Vagrant VM with not so much processing power and I’m using DB which is somewhere in the infrastructure. No cache, no in-memory storage. Everything is as dumb as possible ;)

For testing I’m suing Gatling.io. Great tool with Scala based DSL for test scripts.

We’re set up so let’s do some testing. Goal is to kill all the apps and check what’s the most they can handle.

The test

So PHP died before 50 req/s. It was so disappointing I haven’t checked exact number. Note I’ve done all optimisation on opcache and fpm normal user would do. Nothing crazy tho.

Let’s do Java then. same 50 req/s. No sweat. graph flat at response time about 10ms. Boring. As naive I was pushing by 25 on iteration of test. It took some time but finally got some struggle after reaching 250 req/s. At this point I’m shocked and confused. Mainly because even if I got longer response time I’ve got all the response data when PHP started to throw 500’s and 504’s in my face.

Next step my friend from the office came over and we’ve done some system optimisations on my VM. Then I’ve just

(╯°□°)╯︵ ┻━┻

Last successful test we’ve done got us average 360 req/s. On my VM, on small and slow-ish Mac Mini. And no errors. after that point, when I bumped test to over 400 req/s I simply killed TCP driver on my mac, not application. T bloody CP connections couldn’t be made on that rate on my host. App was fine.

Conclusion

I don’t want to say PHP is bad. It’s still good for frontend and not that high load. But if you really want performance you shouldn’t waste time on PHP IMO. Spring Boot feels like Symfony, all the good tooling is basically done for you.

You’re gaining like 7-8 times better performance out of the box with rock solid stability (I haven’t got even one 5xx from Java app).

Well, choice is yours if you gonna like it.

Multiple PHP versions on OS X

Recently I’ve switched to OSX on my MacBook Air. To keep pace I used XAMPP for first twoo week but today I’ve finally configured my environment as i want.

Requirements:

  • PHP 5.3, 5.4 and 5.5
  • Apache web server
  • Sites in ~/Sites directory
  • Working “localhost” for legacy directory-based projects
  • Different PHP versions for vhosts

Looks simple, but it took me few days to solve all small and big problems.

First what you need is homebrew. On the site you’ll find installation instructions. It’s pretty straight forward.

As an Apache is installed by default in OS X we need install and configure PHP. We want to use different versions per vhost so we’ll use php-fpm.

First we need add dependencies for php-fpm:

Then we can start installing PHPs.

Link operation is linking specific version of PHP to compile paths.

Now when we have installed PHP we need to be able to use them with our default Apache installation. For this we’ll use mod_fastcgi. installation simple as in Debian-ish systems:

Now the funny part with making them work together ;) Most helpful was Gist from diemuzi.

First we need to run three php-fpm in the same time on different ports (I’m using http sockets because.) and set proper user and group for them. Edit this file for each version of PHP you installed.

Second thing is FastCgi configuration for Apache. I’m using Apache 2.2.

Last line includes all .conf files from /etc/apache2/sites-enabled directory. I’m placing there symbolic links to vhosts configured in sites-available directory. Just like you do it in Ubuntu.

Then let’s configure our localhost with PHP 5.4 (Like I said I was using XAMPP so I can live with my webpages in this directory :P)

And sample project with PHP 5.3.

Now when you have domain project.dev configured to points to 127.0.0.1 you can see your web directory.

That’s pretty much all. If I’ve forgot about something or something is not clear please leave a comment.

TODO: i need to check how this setup is working with Symfony 2 projects. I’ll write update soon.

UPDATE for Symfony 2

Basic application works fine – copy-paste config once more:

 

Handling multiple conditions OOP way

Many times in our applications we need to handle multiple conditions which most of the times ends as huge ifs. When we can do it fast & dirty it’s good enough but when we want to code clean we don’t really want huge procedural comparison. Continue reading “Handling multiple conditions OOP way”

Truncate filter in Symfony 2

Fabien Potencier created very useful filter for truncating strings to given number of chars. It’s included in Symfony Standard Edition, but not enabled by default. To fix this place this in any of your service-config files. Continue reading “Truncate filter in Symfony 2”