Hacker News new | past | comments | ask | show | jobs | submit login
PHP: v8.js (php.net)
143 points by barredo on Feb 24, 2012 | hide | past | favorite | 41 comments



Pretty mingtastic API for a first attempt, it's not safe, and is sure to suck performance wise, since all interaction must involve parsing an expression, and coercing any return value back to a PHP type, and with no way to maintain references to native JS objects.

I wouldn't object so much if only the PHP community weren't already known for their tendency to take a bad situation and make it worse: can't we learn from the history of mysql_query() and friends? Decades of SQL injections! There's no reason they couldn't provide a nice "JsObject" type supporting __call() and __get() to allow integration without resorting to interpolating bits of JavaScript code with (probably originating from a user) data, this way at least web developers would be safer from themselves.


We have the use case to render the same mustache [1] templates on the server side (PHP) and on the client side (JS). Problem here is that the template helper view functions have to be written in two languages, PHP and javascript.

Therefore we started two weeks ago to evaluate javascript rendering of mustache templates from inside PHP. First we tried the spidermonkey extension, but had some issues with it. Currently we are using v8js on mac and ubuntu. Works like a charm so far, and we have to write template functions only once.

Now we can use the same mustache templates AND helper functions from within PHP and client side javascript. Even compiled hogan [2] templates work. The templates and javascript files are stored in the PHP APC cache to avoid disk seeks.

So far we are very happy with the results. Here is some php pseudo code how it works with mustache:

pseudo-php-example: \V8Js::registerExtension("mustache", apc_fetch("hogan.js-content")); $v8 = new \V8Js('ContextName', array(), $extensions); $v8->view = array("stuff" => "available in the js template"); $v8->view = array("partialName" => apc_fetch("partialTemplateContent")) $v8->template = "{{stuff}}"

$script .= 'Mustache.render(PHP.template, PHP.view, PHP.partials);'; $renderedTemplate = $v8>executeString($script); echo $renderedTemplate; // prints available in the js template

I recommend checking the v8js samples [3].

[1] http://mustache.github.com/ [2] http://twitter.github.com/hogan.js/ [3] http://svn.php.net/viewvc/pecl/v8js/trunk/samples/


Can anybody give some use cases for this? Would this allow me to use JS libraries (made for node for instance) in my PHP code, or is there something else I could do with this?


Using the same validation code client- and server-side would be pretty nice.


most libs that work with node wouldn't work with this since they're not going to support the node module loading system. You could create some kind of polyfill, but what's the point?

Probably easier to just php `exec()` a node script that does what you want. In fact, if you're considering using this, you'd be better off using node since it will almost undoubtedly perform better.


For a nicer looking wrapper around V8 in a dynamic language, see http://code.google.com/p/pyv8/ -- here your class instances become the namespaces accessible to your JS code and objects are nicely converted back and forth.

I experimented with (py) V8 as an engine for executing certain scripts from Python, but found there was a relatively cost to entering the interpreter. I was also missing a way to pass around buffers and not converting everything to unicode strings (maybe if I could wrap the ByteArray type).


I tried implementing the CommonJS spec (eg require) using this extension in order to integrate javascript libraries such as coffeescript and uglify directly into my PHP web stack.

For simple examples it worked fine, but trying it on real projects such as coffeescript it kept seg faulting.

It's definitely got potential though..


It looks like a PHP extension to embed JavaScript using the V8 engine. The docs are pretty limited. The return value of executing a blob of JS is described thusly: "Returns the last variable instantiated in the Javascript code converted to matching PHP variable type." I supposed the mapping is obvious, to someone :). I'd personally want to know if JS objects come back as stdClass objects or assoc arrays.

It could definitely be handy for a lot of reasons. Seems like it might be handy for embedding a bit of JavaScript testing in your PHP test suite.


I imagine the objects would come back as stdClass as this is the behaviour when decoding JSON objects with json_decode(). I assume other type-mappings will match the behaviour of json_decode() too.

I can't think what the result would be if the last variable instantiated in the JavaScript code was a function though; perhaps null, or an exception would be thrown.


I'm in complete agreement with you. Having a CI server is great for PHP work, but it would be better to have the one CI server process both PHP and javascript unit tests together.


Last time I looked I don't remember seeing any bindings to the PHP environment.


This is interesting, and I saw the one Example (Hello World) they have on the site.

So I guess my question is, why? What's a real use case example of why'd I want this? PHP isn't syntactically more tragic than JS. JS doesn't have so many more libraries than PHP already has? I can't see why someone would use this? Maybe to hook into GWT librarieS?


The only "why" that I've been able to surmise is for people using PHP to scrape/interpret content from existing webpages. But I only make that assumption looking at the itches that Jani (the lead behind the PHP v8js) has been scratching recently: http://pecl.php.net/~jani/patches/


Unfortunately, there are some bugs with the variable passing. You should be able to pass an array of variables to the V8js object and have access to them under PHP js object. However, the values are currently set to null.

In my experimentation I wanted to see [in php after js execution] all the variables created in the global scope. There are two ways to do it, pass the flag to the V8js constructor to make executeString return associative arrays and add "this;" to the tail of the scripts you execute. Or, append "JSON.stringify(this);" to the tail of the scripts.

The first method will return everything including references to print, var_dump, sleep and exit methods that are bridged from PHP.

The stringify method will give you just the variables without the method references but tends to leave you with empty arrays if all your array indices point to null values. Which is misleading if the result is "someVal: {}", verses "someVal: {'foo': null, 'bar': null}".

What it misses most, is the ability to bridge your own method calls. Would be nice to be able to register a method call in JS that executes a user defined PHP function.


That is a great idea, a scripting language riddled with design flaws integrated into a scripting language riddled with major design flaws, gaping security holes, a over-zealous and wrong tokenizer, extra transparent features that will fuck you over where they can, an incompetent maintainer, a terrible API..


Great, just as I'm moving away from PHP and diving into Ruby (I've fallen for it's OO charm), they have to release such a wonderful engine. This is amazing though, well done.


I have to say: this is incredibly intresting! I woulbe be curious how one can pass-in variables.

I'm afraid you can not get much out of the great features of JS. Event drivenness..

Anyway, this blows my mind!


Very interesting. Although, the last release is more than a year old. That does not bode well... http://pecl.php.net/package/v8js


So what is the usecase of this project?


do. not. want. If you think this is anything but the worst idea ever - trust me; you're doing it wrong.


I wouldn't want it as a base for developing something new, but if you are knee deep in some old, smelly codebase that should be fixed yesterday, I can definately see how it could be usefull.


Can you elaborate?


Let's see. Practically - a web templating language with weakly-typed bolt-on OO 'featurettes' now has an embeddable, weakly-typed, object-oriented scripting language. Hello run-time heisenbugs that can NEVER be unit tested nor debugged.

Anecdotally - let's face it; there is no shortage of crappy php and javascript out there. This is an open invitation to merge the two into one extraordinary megaclusterfark.


Yes, but it could still be legitimately useful. Show me a powerful technology and I'll tell you how it can be misused, but that won't invalidate its potential usefulness.


one possible use can be executing some JS code even if JS is disabled in browser


yes but that would require server to know that which again requires some sort of ajax which cannot happen because js is disabled!


<noscript>


apparently I have to spell it out to the downvoter...

    <script src="/client-side.js"></script>
    <noscript><img src="/server-side.js"></noscript>
...which fulfills the requirement of "executing some JS code even if JS is disabled in browser".


yes, that seems correct, also just to make it clear, i can't even down vote yet :P so it wasn't me :)


Well that just makes me go WTF.

I genuinely can't think of a way this will be used which will be positive for PHP.


In theory, it will have the exact same use as the rubyracer gem (http://rubygems.org/gems/therubyracer). Possible uses of that are compiling coffee script using the official compiler or running the same form validation code on both the client- and the server side.

In general I'd be cautious about both the ruby racer and this as you are practically embedding a garbage-collected heap into another garbage collected heap, exchanging references between them (more so for the ruby racer - the PHP extension here is way less integrated).

This is memory errors waiting to happen.


"or running the same form validation code on both the client- and the server side."

That sounds great until you realize that you usually do a lot more validation on the server than on the client (is the username taken, is password correct, etc etc). So you would still have to use PHP for validation (in most cases).


Sure, but only for the cases not covered by the JS.


I was trying to say that you don't really gain anything in this case. You would load some JS file (which would probably have to be written in a way that it could be used this way) just do do some simple validation (if (someField!='') for instance). Doesn't seem like worth the bother to me.


This extension has been around for a long time, just like the PHP Lua extension.


Yo dawg, I heard you like javascript.


I have been doing a lot of work with PHP recently, and reading through their library docs, it seems to me like they will put anything in a core extension, regardless of whether it's something that really belongs there.


This isn't a core extension, it's a PECL extension--see http://pecl.php.net/package/v8js. PECL extensions are not distributed with PHP. You have to explicitly install them if you want to use them.

I think sharing code is always better than not sharing code. If you run into a use case where this would be useful, then you can just grab it and install it.


> I have been doing a lot of work with PHP recently

If you've been doing a lot of work in PHP recently, then you should be compiling your own PHP. Which gives you the option of disabling every extension. The PHP core is actually very lean. Virtually everything is an extension. They even have a nifty flag to disable everything.

I like having the option of compiling a bazillion extensions in the binary if I want to. Even though I never enable anything beyond the basic stuff I need.


Stuff like this with PHP just reminds me how nice the module loading systems other languages use to handle this sort of thing.*

PHP - forgot something? Best re-compile so I can access the module's massive list of global functions.

Python, Ruby, Node, etc. - `import/include/require module`

* because Pear is basically a waste of time.


What?

Have you tried to install something using pip for Python? How about npm for Node?

Those package management programs compile stuff on your system all the time. Same as PECL extensions.

The ecosystem for Python, Ruby, Node works exactly the same as it does for PHP. Please leave your random PHP hatred at the door.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: