What are use cases for V8 in PHP? - php

PHP has embedded V8 JavaScript engine, http://www.php.net/manual/en/book.v8js.php. I was wondering what are possible use cases, esp. considering that PHP is synchronous and JavaScript is asynchronous.

A powerful feature of this extension is that the same code can be used both client and server side, reusing implementations of the same code in PHP for server side and js client side.
A possible use case is for providing server and client side validation using the same JS code. Client side, the code would be run in the browser, and server side it's executed using V8JS.
Other potential uses could be templates or any other business logic that's needed both client and server side.
It seems like you'll still be in uncharted territory here, though. I haven't seen any libraries use V8JS for anything like this.

One of the ways I am using JS integration within PHP is to provide a simple manner for end users to safely execute user-supplied code (a.k.a. scripts) within a PHP-based app. With the implicit isolation, one can limit the inputs and functions available to protect both user privacy and system security while allowing a wide range of user-defined scripted actions within the server context.
I must admit that seeing executable javascript code in database records is a bit unnerving at times! You do get over it though. :)

One use case could be server-side rendering for javascript templates or frameworks, SSR for short.
One could write their templates with a javascript framework like Vue.js or react and render it with v8js.
Once php has rendered the template and sent it to the browser the javascript framework could pick this up and make it interactive.
Two benefits here are faster loading web apps and no annoying javascript page flicker.

For building crawler which extracts useful data from HTML emulating Javascript runtime is especially useful, because some HTML data may be hidden/mangled by Javascript code. So unless you would like to write Javascript parser in PHP yourself - the only option is to use V8 engine built already with that purpose.

PHP and Javascript are languages, it doesn't make sense to say one is synchronous and one is not. Informally when one says that, they mean that most of the libraries around that language that use I/O use async/sync IO.
In the core language and V8, nothing is asynchronous.
Why to use it? Javascript on V8 is orders of magnitude faster than the canonical PHP implementation (note that there are other PHP implementations, like Facebook's HHVM) while still being just as powerful scripting language. Normally you would be forced to write a C extension for PHP to get raw performance.

Sorry to bump / add to an ancient question, but a fairly obvious use case in the Web 2.0 / 3.0 era is going to be "when file_get_contents() just won't cut it."
Although it may not be the best choice, PHP also isn't the worst choice for bots, spiders, scrapers, etc. And more and more web pages aren't complete unless the JavaScript on them is executed / rendered.

Related

How much PHP for AngularJS

I'm relatively noob to the world of web developpement, and after learning the basics of HTML5/CSS3/JavaScript/jQuery I've started to learn AngularJS.
The problem is that as I am learning AngularJS, I don't understand what will be the point in learning a server-side language like PHP, it seems like AngularJS can do all the job (UI, views, routing, ...)
I think that the only reason would be to store data (but even that, I can use JSON files, no?)
and if it is, how much PHP do I need to learn? (or which parts of the language)
Thank you and sorry for my english.
Angular is a tool for a specific sort of job. It is not the tool for every job, and neither is PHP.
If you are writing an application that can live client-side, then you can certainly generate all of the dynamic components you need with Angular. There are many web applications out there that are entirely client-side. There are even more that function client-side and talk to a simple API server for their back-end.
If you are creating a web page that is not interactive, then there is little reason for something like Angular. There are benefits to having the DOM filled with content ahead of time. SEO is usually the biggest reason, but you might also consider clients that have disabled JavaScript (if you care about those).
Are you building something that is interactive? Consider a heavier client-side framework like Angular. Are you building a web page that is content-driven? Consider rendering your pages server-side. In the end, you will likely end up with a mix of both anyway.
A large consideration is security. Everything client side is exposed to the world. If the back end is just data storage without validation or protection except as written inside the client, a malicious user could push whatever data they wanted into your site. In addition if you are exposing code that is the core of a business inside the client, every user can see that as well.

PHP MVC with pure Javascript View : good practice?

My question might not be understandable enough, so let me explain the situation :
I'm working on a big ajax webApp built, server side, with PHP using CodeIgniter. This framework saperates clearly models, controllers and views. The view files are rendered in HTML and then sent to the client that does some js treatments on it (like attaching events).
This way of working seems strange to me, as it separates the view between the server side and the client side.
I was thinking about moving all the View treatments to the client part that will build dynamically its html in js. The server side will then send only raw data.
I worked this way on smaller projects, and I was really happy with the result (easily understandable, portable and reusable).
Is it a right way to implement an MVC app ? Any advices around that reflexion ?
I've done pretty much what you are describing on a fairly large data services app as an internal application. In my case I was using ExtJS for the client-side rendering/views, and was communicating to a C# WCF endpoint exposed on the web server. Essentially requests were made/submitted and responses were serialized to/from JSON. It ran very smooth, once some kinks were worked out. The original author had written a custom serializer to do direct results from their data layer directly... this leads to a lot of extra data going down the pipe. As long as you are judicious with your payload data it can be very effective.
Some caveats though...
You should probably avoid this if you expect users without javascript enabled to be able to access the site (anything involving money transactions from external users).
You will want to document your methodology as clearly as possible.
Finding developers for maintenance tasks after you have implemented your application will be very difficult. (many server-side devs are shy of, scared of, or just plain inneffective with JS skills.
For the most part it's a toss up, I find that most people at least have JS enabled, but may have other things blocked off. AJAX/XmlHttpRequest supports is nearly universal at this point.
As to templating for client-side display, there are a few options there (but that's a separate discussion).
Building JavaScript views works fine within the MVC pattern, since your view is not mixed in with your business logic or model.
However, there are a couple drawbacks to using full javascript views. Mainly it eliminates the ability for graceful degradation if the client has javascript turned off. Also, some browsers (IE) don't have a very fast javascript engine, which will make your page load more slowly. It is true that some of the view is separated between the client and the server, but it kind of makes sense when you think about it.
In most cases the HTML that you send to clients is the same for everyone (unless you are doing browser detection on the server side). However the JavaScript routines are different. If you are using a library like JQuery, this will be hidden from you, but the code that is running on each client may differ greatly. One example of this would be the XMLHttpRequest that is used by firefox/webkit etc browser and the active x control that is used by IE. Since the html portion of the content is the same for everyone it makes sense to build on the server, and since the JavaScript portion of the view may differ, it make sense that it is built on the client side.
HTH
I started using the same approach: JavaScript for the user interface layer and PHP for the database access layer. I'm using AJAX to pass all the data back and forth between the 2 layers. So far, AJAX has occasionally frozen on me, but it has been speedy enough most of the time. So I guess it'll work well enough.
(The result is that my code has gone from 90% PHP with 10% JavaScript...to 65% JavaScript with 35% PHP.)
I've also separated the code for my page views from the code for my triggered event action functions. So I like to think that I have an MVC arrangement now (even though I'm not using an off-the-shelf MVC framework like Backbone.js).
I'm not using HTML templates, though. I don't think it feels natural to have 100% separation between HTML and programming. I think simple programming loops, conditional statements, and JavaScript triggers all go nicely with HTML.
If you will think it in the way that there is the main view that creates the html/js engine and couple of ajax views with the data streams - it will be quite OK in MVC terms imo.
Is there anything more dynamic going on on the site itself? Does it do more AJAXy things, dynamically refresh parts of the site etc.? If so, it may be reasonable to have a Javascript-only site.
Since this is not how the web traditionally works though, sending HTML from the server is still the baseline. If your pages are basically static, if you want to serve older clients, an audience that may have disabled Javascript, an audience that may have accessibility problems with Javascript-only pages, alternative clients that cannot understand Javascript or search engines, you should serve HTML pages from the server. There's nothing wrong with it, it's straight forward, simple and foolproof. There are many things to consider when reinventing the wheel in Javascript on the client side. Unless you have a good use for the potential this offers (see for example the highly dynamic Facebook or Twitter pages), it may be more trouble than it's worth to your users.
It sounds like you are one step away from going from the MVC pattern to the MVVM pattern.
MVVM is ideal for complex user interfaces (which is exactly what you would be creating with all the AJAX and JavaScript and whatnot) because in this case your HTML view will be able to act as the controller via JavaScript. There is a library (warning: I've never used it but it looks promising) for this called Knockout JS.

Creating views with PHP for couchDB

I have started to try out noSQL databases now and are currently testing out couchDB. Seems like a good solution, but I really get some headache when I follow available examples on how to create views (queries) to select documents from a database and sort them.
Everything I can find is regarding JavaScript and it would be great to take part of some examples for PHP since that is the language we will use.
So, how do I create views using PHP for couchDB?
As far as I know, the equivalent of the SQL language that would be used for a relationnal database is, for CouchDB, Javascript.
So, if you want to create some "query", or "view", you have to do it in that language : it's the one that's understood by CouchDb.
PHP and CouchDb are totally independant : the only thing is that :
PHP can send requests to CouchDb
and get results
But what happens on the CouchDb side is independant of your PHP script -- and there is no PHP on the CouchDb side.
The only way to filter results using PHP would be to :
Request more data from CouchDb than you need
And throw away, from PHP, what's not needed
But, obviously, that would not be an efficient solution...
Javascript is privileged as a CouchDB view server only because that's what's bundled with CouchDB. There are view server implementations for many other languages/runtimes, including PHP.
JavaScript (CouchDB native)
Common Lisp
PHP
Ruby (fork)
Python
couchdb-python
couchdb-pythonviews
Erlang
built-in view server
erlview
Clojure
Perl
Chicken Scheme
Coldfusion
Haskell
OCaml
I think you need to understand Javascript's stance in CouchDB. Javascript isn't a target language like PHP, Ruby, etc. Javascript is more equivalent to SQL here. The javascript is server-side and CouchDB itself actually executes it. This is what you use to do map/reduce and build views and such.
Try PHPillow man
Here's a very short introduction to it: http://www.catswhocode.com/blog/getting-started-with-couchdb-tutorial-a-beginners-guide
If you check out the SVN of PHPillow, there's more information in the 'docs' folder

Embedded script languages for PHP?

i was wondering if anybody knows of a nice scripting language that can be embedded into php?
Javascript would be favorite and although there are several attempts they are either much too shaky/slow/outdated (phpjs, j4p5) or a real pain to get up and running on shared hosts (pecl spidermonkey).
The background is: I would like to have a language that is used to control php on the server but it should also support some logic, so yaml, xml or json just isn't enough. I've looked into LUA interpreters and mediakwiki's "Winter" but they all either rely on external engines or have powerful binding whatsoever.
pecl spidermonkey binding's appears to be the most complete where you can register vars, functions and whole objects to the js-engine. Does anyone know of any system or language that might come close to what I am looking for?
best
rolf
I've not seens many engines that allow another scripting language to be enabled in PHP :-(
Even on PECL, there doesn't seem to be lots of entries (see the "languages" category, for instance : only one, which you already know)
And on PEAR, I don't even find anything that would match your criteria...
I've played with Spidermonkey a bit (see this article on my blog, in french), and it's kinda fun, yes. But it was not really stable a couple of months ago when I wrote that article -- and there have only been a few commits since. So, I understand why hosting companies would not provide it on their servers...
Even if I'd like them to : could be great to allow non-PHP developpers to develop scripts for your application !
A question though : why do you want/need another language than PHP ?
What I mean is PHP is already installed on your server, you obvisously have experience with it, and it's a quite powerful language... So why do you want/need to work with something else ?
Using PHP's eval, you can even think about executing "dynamic" PHP code (Yep, eval is eval and all that, I know ^^ )
Another option, using stuff like "exec" and the like would be, if you are on a Linux server, to launch some kind of shell-script ; but I would definitly prefer coding in PHP than shell, and I'm certainly not the only one ^^
Anyway, keeping an eye on the answers you might get, which could interest me quite a bit too ;-)
I understand your concern. Even for trusted sources, PHP provides more access than is necessary to the whole environment of the web request. Even if the scripters are trusted and even if they can only harm themselves with a scripting error, a more constrained scripting environment would be easier for them to use and easier for you to support.
You want something that can be sandboxed off, that can only access resources you explicitly assign to its scope, and that executes in a "play within a play" runtime environment rather than in PHP's own.
One approach is to use a web templating language for user-submitted scripts. These provide a certain amount of control (variable assignment for example), and close off other options, for example you can't write an infinite loop. I've used Velocity for this purpose in Java applications; I think something like Smarty might work in PHP, but I don't have direct experience of using it for that purpose.
Another approach, if what the scripts are required to do is constrained by the domain, is to implement a Domain Specific Language (DSL). I mentioned that in this answer.
Apart from that, I don't know of any pure-PHP implementations of scripting languages. It's something I'd be interested in myself.
Symfony has the ExpressionLanguage component:
The ExpressionLanguage component provides an engine that can compile
and evaluate expressions. An expression is a one-liner that returns a
value (mostly, but not limited to, Booleans).
...
The purpose of the component is to allow users to use expressions inside configuration for more complex logic. For some examples, the Symfony Framework uses expressions in security, for validation rules and in route matching.
An example of the language is below:
# Get the special price if
user.getGroup() in ['good_customers', 'collaborator']
# Promote article to the homepage when
article.commentCount > 100 and article.category not in ["misc"]
# Send an alert when
product.stock < 15

Should PHP frameworks generate JavaScript?

I've noticed that a PHP frameworks; Zend, Cake, and Symfony; seem to either generate JavaScript or allow it to be embedded as a string into the PHP itself. Is this a good idea? From people who've used these frameworks/libraries, what has been your experience working with the Ajax and JavaScript helpers? Has it been easy to maintain? Does it cut down on development time?
No it is a bad idea,
Generated javascript usually means that the site won't even function without it (like many asp.net sites). If you want to do more complex things or want to enhance accesibility there is no other way around than clearly seperating HTML from CSS and Javascript.
Seperating Javascript also makes your code more maintainable as you do not need to have your client side frontend developers mess with your PHP code and the other way around.
The best way to use Javascript is to first let php generate your html, then at the bottom of that page include your javascript files and use functionality like onDomReady. This also doesn't force you to use a particular library just because your framework is using that as base for its generated Javascript.
This is quite a subjective question, but personally, I wouldn't want a back-end framework to do this for me. It's better to keep a clean seperation between business logic, presentation, and client-side UI behaviours for a number of reasons:
More maintainable applications.
Easier to test individual components.
Easier collaboration. Different skill-sets can work on different areas.
Should help ensure your application does not rely on JavaScript in the end users environment.
Personally, I like to write my Javascript by hand, unobtrusively so that i just have to add an extra event to document.domReady with for example the correct parameters. That little trigger function then gets the ball rolling.
Best practice of the day:
Keep frontend-code and backend code
untangled as much as you can
I would say it depends, like anything. There is certainly some value in having "smart" server side widgets. For example, a widget that "knows" how to update itself through AJAX, or a form which can handle client side, and server side validation. The latter is an example of which it would be costly and time consuming and error prone to rewrite boring validation code in the client. It doesn't require rocket-science javascript, so as long as your framework can handle it unobtrusively, I would actually advise this route.
Additionally, framework code that will handle GUI stuff also (a la ext or something similar), is also not a bad a idea.
However, anything more complicated than that, please use Javascript itself.
I personally love writing my own Javascript so I don't really want it written for me, but I don't see it as being particularly 'dangerous' or 'harmful' to have frameworks that do it for you, as long as it is properly done. My biggest problem with them is that most of them will work as long as you want the standard behavior of a feature, but as soon as you want something a little different to meet your project's needs better it takes so much work to customize it you would have been better served to do it yourself. At least that was my experience with CakePHP's javascript automation.
My experience with the Javascript and Ajax helpers in CakePHP has been very positive.
They have allowed server-side developers to prototype and build features that otherwise would require someone with real client-side experience to do, all without having worry about the quality of the javascript code they "write" and leaving the real front-end engineers free to focus on the advanced client-side features.
It's not a good idea for the PHP to generate Javascript. The only javascript I would recommend exporting is simple JSON assignments like the following:
<script type="text/javascript"><!--
var MyNamespace.info = <?php echo json_encode($info_array) ?>
// --></script>
This is the easiest way to sanitize PHP information and let it be accessible to javascript on the client. However, anything else should be written in actual JAVASCRIPT FILES that are referenced with tags at the head of the document. The only other appearance of Javascript from server-side files, that I would say is alright, is stuff placed into "onclick" and other such attributes.
The rationale for this is that the Javascript should be written and maintained by front-end people who know Javascript, and the site should be able to work (at least partially) without javascript. There is no reason to generate spaghetti Javascript inline.
Check out my PHP framework, PHP On Pie (http://phponpie.com) for an example of how to implement this properly. It keeps the JS and PHP separate, except when exporting JSON as shown above. However it also provides conventions for easy interoperation between the client and server via AJAX.
I believe you should keep languages apart. Even though they can complement each other. That way you can pick the implementation of said language and create a mix that fits you perfect.
I think there is definitely a place for generated javascript. (1)
The number one reason for generated javascript is ease of maintenance. Any dependencies are explicitly encoded and configured from the framework (PHP, ruby, scala, python) itself. For instance if you move your assets or change the upload directory, just update the configuration and watch things Just Work.
Need client side input validation to take some load off your server? (2) Let the framework generate correct validation code derived directly from your data model for you. With generated, javascripted population your framework can serve pre-rendered, static HTML forms from the cache. This could be a huge win if your forms contain lots of selects and options.
1) Assuming that the client has decided that it's OK for the site to depend (more or less) on javascript, with all the caveats that entails. Graceful degradation may or may not be possible or desirable.
2) You need server side side validation too, but you knew that, right?

Categories