Some code ports to Mojolicious, just for fun.

Today is a relatively minor holiday in the US, but I had work off all the same. I found myself experimenting (when I probably should have been working on my YAPC::Brazil talk :-/). Thanks to today’s PerlWeekly (you are a subscriber right??), I found out about an interesting post by Johnny Moreno which creates a tiny json service backend using Perl. Of course it uses to do so, which made me curious what a Mojolcious port would look like.

This code ported relatively nicely. I made some tiny improvements to increase database connectivity (even allow for multiple worker processes) and also to decouple some of the logic for easier testing. The result is this:

You’ll notice I have a few helpers, which are for the purposes of this discussion simply controller methods, and one route. Note that the state declaration means that the db helper returns a cached instance of DBIx::Connector, which given the nature of that module is what you would want.

The major thing I wanted to highlight in this porting, however, is the ease with which Mojolicious can properly render a JSON response. Of course a more direct port is possible (if say you wanted to use JSON::XS for a faster conversion), but I find the simplicity of this code appealing personally.

Of course, I then decided to take on the challenge of the poster’s next work, and since that post revolves around building a complex SQL query, I thought I might try out SQL::Abstract. I have used that module indirectly via DBIx::Class and while I’m happy I tried, the results are a little more mixed.

The good parts are that the code (and certainly the generated query itself) would be much more testable. I’m not quite sure that SQL::Abstract was actually beneficial in this case, but assuming a real-world backend might have other complex queries perhaps the end result would be preferable. Anyway, here is that code:

Of course, since I don’t have any actual database, I couldn’t really test these out, and perhaps they have bugs. That said, I hope they can be a model for porting other code from to Mojolcious and other more modern tools. I’m not going to sit in judgement of those who continue to use the “old standbys”, however, I hope that they chose to do so out of personal preference and not for lack of examples which might help.



As cool as this posting is it is hard to read the code example because some of the interesting lines scroll off the right side of the display. In the second example the scroll bar is sometimes off the screen. When reading code examples it is nice to be able to see the whole code at once.

Maybe that’s a feature of the web interface. Still we often end up having to make accommodations for the problems of our tools.

Leave a comment

About Joel Berger

user-pic As I delve into the deeper Perl magic I like to share what I can.