Focus on Groovy
I almost initially called this series “Groovy for PHP developers”, but decided that because Grails was really the ‘web’ portion of the Groovy/Grails combination, and that PHP was very much web oriented, I relented and went with “Grails for PHP developers”. However, in retrospect, this may have been a mistake. Why?
Primarily because you’ll spend much of your time in Grails writing Groovy code (or Java, perhaps). As such, a good understanding of the language is essential to get the most out of a Grails project. So, with that in mind, this installment is going to cover some of the basics of the Groovy language. We’ve covered a bit on arrays before, and we’ll revisit them again today, along with other Groovy goodness.
Back to basics
Groovy is about as basic a language to get started with as any. For today, rather than running things from the command line, I’ll show some screenshots of the Groovy console. If you have Groovy installed, you should just be able to type ‘groovyConsole’ and get a popup window looking something like this:
This is a small interactive console which is handy for trying some quick concepts, as well as doing a bit of on-the-fly inspect of variables (more on that later)
Setting variables
We’ll start off with something slightly more advanced than “Hello World”: we set a variable and then print it out like so. Hit CTRL-R or use the “Script” menu to run the code after you’ve entered it below.
Neat, eh? All we did was assign 3 to “a” then print it out. No $ around a variable name – arguably simpler than PHP! However, Groovy’s simplicity can be as much of a potential headache as PHP’s. Here’s how.
If you’ve ever done Java before, you’ll may have run in to the issue of redefining a variable’s type. A variable that’s “x” holding a number then later holding a string. Java’s strict enough to prevent this. It may have been what you intended, or perhaps not. Java won’t allow it. It’s fairly common in the PHP world however. I’m certainly not claiming this is a good thing to do, but if you’ve dealt with PHP code for a while, you’ve likely come across this practice. It’s especially prevalent in procedural code that reuses the same few placeholder variable names for different purposes. And, for better or worse, Groovy allows it as well. Example:
So, word of warning – be as careful with your variables in Groovy as you need to be in PHP.
It’s array-ning, men
PHP has one basic type of array structure, which can be used for both zero-based indexed arrays and associative arrays. Groovy splits these up in to two different concepts: lists (zero-based arrays) and maps (associative arrays). A standard list definition looks like this:
We simply put the elements we want in the [ ] markers, and separate with commas. It’s not *that* different from PHP’s syntax ($a = array(8,6,7,5,3,0,9) ), but is a bit less typing. A difference from PHP you’ll notice right away is when we print out an array – we get the elements in the array, not the help PHP goodness of “Array” dumped to the screen. Yes, var_dump() and print_r() are your friends in PHP, but it can get a bit tiresome.
Because a list (and a map, and pretty much everything else in Groovy) is an object, the syntax for manipulating the list is object oriented. Let’s join the list elements together.
Notice the println this time instead of print? We’re printing the data and adding a line feed afterwards. In the example above, we join the elements of the list together first with nothing between them – we simply get 8675309 as a list of numbers. By changing the join parameter to “-” we get 8-6-7-5-3-0-9. Same functionality as PHP’s join (and alias implode) but syntactically different.
What do maps look like? Similar, but with keys in them.
Notice the key name precedes the value with a colon (:) as the separator, instead of PHP’s “=>” syntax. Also notice that the keys do not have quotation marks around them. You *can* have them around, but Groovy doesn’t seem to mind either way. The text values do need quotation marks around them, however.
Groovy allows for n-level nesting of maps and lists as well. Check out the example below:
Let’s try to redefine the ‘name’ element of our map. If we do not use quotation marks in this context, we’ll get an error.
See the error about a Missing Property? What’s going on under the hood is that Groovy is compiling the script down to a Java class file, and all variable references become properties of the class that was created for us by Groovy (we didn’t declare any class – we just have a few lines of script). Because there’s no value for ‘name’ Groovy is assuming that we want the ‘name’ which would be part of the class. It’s as if Groovy is looking for the PHP equivalent of $this->name (which would be this.name in Java/Groovy) and because we haven’t set it – indeed, it doesn’t exist! – Groovy throws this Missing Property exception. To get around this, we have to use quotation marks, as so:
We can also use variables as keys, like so.
There’s more with variables and arrays I’d like to dig in to, but I need to save that for a future article. In the meantime, have fun getting started with lists, maps and variables, and send in any questions you have about Groovy. I’ll do my best to answer them.








So I enjoyed your article, it is interesting hearing the impressions of a seasoned PHP developer on Grails. Have you much experience with Object Oriented development? I might reccomend reading a bit of Eric Evans book Domain-Driven-design…
It doesn’t map one for one to Grails. But reading Eric’s book would give somone who is new to the DDD concept an avenue to really take in the Zen of Grails pretty quickly..
Keep up the series. I look forward to commenting as you go along. And you have yet to step into the real deep dookie of it all….
And alot of us Java guys really enjoy the strong typing, though we have a fondness for the speed and quickness dynamic languages can provide…
-Dxx
Nice to see how groove behaves on error reporting. Will this behavior be improved? Anyway, i guess i should really do JSP instead of Groovy.
I have quite a long history with PHP and recently started with Grails so this was interesting for me.
Biggest problem I have with Grails, though, and I really can’t see how anyone gets around this neatly, is nested arrays in forms that populate appropriately in the controller.
eg.
In PHP this would populate a $invite array with 2 items, each with two items (‘name’ and ‘email’).
But in Grails the ‘[' and ']‘ become part of the name and are never evaluated as an array.
Have you come across this and how did you work around it?
Paul.
As great as many things are in Grails, array form handling in Java (in general) sucks, and the Java people don’t seem to even realize how bad it sucks. What needs to happen is someone to create a global beforeFilter to analyze the incoming stuff, scan for [] and handle appropriately – nesting would be even more awesome. However, the whole 0-indexed vs string-indexed stuff would come up as an issue cause there’s no major distinction in PHP, but there is in Java.
I’ve not found a good solution yet. :/ If I get the filter written I’ll release it.
I have just come across the method of using ‘ListUtils.lazyList’ to create a list that is supposed to dynamically expand with a factory that creates the dynamically created list entries but so far I’ve not been able to get it to parse the ‘invite[1].email’ form fields as anything other than a single variable (as you say above, it’s not parsing them into a list).
Odd thing is that the posts I’ve read all seem to think this approach works – they’re mostly using it for dynamically expanding forms, which is kind of what I’m doing.
I only ever seem to get “No such property: invites[1].email for class” no matter what I try.
Nice article…
one thing am not found yet is deployment…
compared to LAMP where PHP sit on there
Are there ISP which over JVM (Grails, JSP, JRoR) with same price with LAMP hosting ??
Roughly that you use IceTea on Mandrive, could be nicely if there were free/economic or equaly same with LAMP hosting over.