Getting started¶
About¶
php-v8 is a PHP 7.x extension that brings V8 JavaScript engine API to PHP with some abstraction in mind and provides an accurate native V8 C++ API implementation available from PHP.
Key features:¶
- provides up-to-date JavaScript engine with recent ECMA features supported;
- accurate native V8 C++ API implementation available from PHP;
- solid experience between native V8 C++ API and V8 API in PHP;
- no magic; no assumptions;
- does what it is asked to do;
- hides complexity with isolates and contexts scope management under the hood;
- provides a both-way interaction with PHP and V8 objects, arrays and functions;
- execution time and memory limits;
- multiple isolates and contexts at the same time;
- it works.
With this extension almost everything that the native V8 C++ API provides can be used. It provides a way to pass PHP scalars, objects and functions to the V8 runtime and specify interactions with passed values (objects and functions only, as scalars become js scalars too). While specific functionality will be done in PHP user space rather than in this C/C++ extension, it lets you get into V8 hacking faster, reduces time costs and gives you a more maintainable solution. And it doesn’t make any assumptions for you, so you stay in control, it does exactly what you ask it to do.
With php-v8 you can even implement NodeJs in PHP. Not sure whether anyone should/will do this anyway, but it’s doable.
Demo¶
Here is a Hello World from V8 Getting Started developers guide page implemented in raw php-v8:
<?php declare(strict_types=1);
use V8\{
Isolate,
Context,
StringValue,
Script,
};
$isolate = new Isolate();
$context = new Context($isolate);
$source = new StringValue($isolate, "'Hello' + ', World!'");
$script = new Script($context, $source);
$result = $script->run($context);
echo $result->value(), PHP_EOL;
Installation¶
Requirements¶
V8¶
You will need a recent v8 Google JavaScript engine version installed. At this time v8 >= 6.6.313 required.
PHP¶
This extension requires PHP >= 7.2. Last version that supports PHP 7.1 is v0.2.2 and for PHP 7.0 is v0.1.9.
OS¶
This extension works and tested on x64 Linux and macOS. As of written it is Ubuntu 16.04 LTS Xenial Xerus, amd64 and macOS 10.12.5. Windows is not supported at this time.
Quick guide¶
Docker¶
There is default phpv8/php-v8
docker image with basic dependencies to evaluate and play with php-v8:
docker run -it phpv8/php-v8 bash -c "php test.php"
Ubuntu¶
There is
$ sudo add-apt-repository -y ppa:ondrej/php
$ sudo add-apt-repository -y ppa:pinepain/php
$ sudo apt-get update -y
$ sudo apt-get install -y php7.2 php-v8
$ php --ri v8
While pinepain/php PPA targets to contain all necessary extensions with dependencies, you may find following standalone PPAs useful:
Building php-v8 from sources¶
git clone https://github.com/phpv8/php-v8.git
cd php-v8
phpize && ./configure && make
make test
To install extension globally run
$ sudo make install