PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

MentalJS for PHP

Note: This article was originally published at Planet PHP on 18 November 2012.
Planet PHP

I decided to convert MentalJS to PHP so that the parsing can happen server side and maybe even later on allow JavaScript execution inside PHP. I found PHP really slow and has poor support for creating parsers. As an example I found that parsing jQuery in php was around 3.6-4 seconds whereas JavaScript was 100ms, I noticed an improvement when I used .= instead of str = str .str but it's still pretty slow. Adding multi-byte characters was even worse mb_substr is so slow it can fail to parse even small amounts of JavaScript. I suppose my code was optimized for JavaScript so there's probably a little bit of work to optimize for PHP. PHP closure support is quite pathetic and feels hacked together since variables defined in a parent function aren't available to a child function which is odd and you have to use the aousea statement in the function definition WTF. But anyway less moaning about PHP.

The PHP class is available here:
MentalJS Class

Here's how to use it:

$js = new MentalJS;
echo $js-minify("function x () {\n\n\n\n\n x = 1\n3\n\n}");

At the moment it supports minifying, parsing, syntax checking and getting a parse tree of the parsed data. In future I may support aoexecutea to allow JavaScript execution in PHP but before that I need to find ways to speed it up to get it closer to JS parse times. I've also done a simple demo so you can check it out here:
MentalJS PHP demo