<?php
$isolate = new \V8\Isolate();
$context = new \V8\Context($isolate);
$source = new \V8\StringValue($isolate, "'Hello' + ', World!'");
$script = new \V8\Script($context, $source);
$result = $script->Run($context);
echo $result->ToString($context)->Value(), PHP_EOL;
//result is last statement executed
<?php
$isolate = new Isolate();
$context = new Context($isolate);
//Load our app.js file from disk
$sourceString = file_get_contents(__DIR__ . '/app.js');
$stringValue = new StringValue($isolation, $sourceString);
$source = new Source($stringValue, null, $cachedData);
//Compile it (add caching of compiled code here)
ScriptCompiler::Compile($context, $source, CompileOptions::kConsumeCodeCache);
//Here's some state I prepared earlier!
$jsonInitialState = json_encode($preparedState);
//Make our dirty PHP values into v8 ones
$initialStateVarName = new \V8\StringValue($isolation, '__INITIAL_STATE__');
$initialStateValue = new \V8\StringValue($isolation, $jsonInitialState);
//Get the JS contexts global object and inject our prepared state
$globalObject = $context->GlobalObject();
$globalObject->Set($context, $initialStateVarName, $initialStateValue);
//Execute
$result = $script->Run($context);
echo($result); //Gimmie that DOM
//JS
const initialState = (global && global.__INITIAL_STATE__) ?
global.__INITIAL_STATE__ : {};
const store = createStore(
rootReducer,
initialState,
enhancer
);
const app = (
<Provider store={store}>
<App>
</App>
<Provider>
);
if(isServerSide) {
global.__RESULT__ = ReactDOMServer.renderToHtml(app);
global.__INITIAL_STATE__ = JSON.stringify(store.getState());
}
else {
ReactDOM.render(app, document.getElementById('app'));
}
$phpSync = "Synchronous";
echo($phpSync);
getJsSync().then((sync) => {
console.log(sync);
});
(very simplified example)
<?php
//Create our "fetch" function
$fetch = function (\V8\FunctionCallbackInfo $args)
{
$context = $args->GetContext();
foreach ($args->Arguments() as $arg)
{
$out[] = $arg->ToString($context)->Value();
}
$contents = file_get_contents($out[0]);
$args->GetReturnValue()->Set(new \V8\IntegerValue($args->GetIsolate(), $contents));
});
//Make a v8 template out of it
$fetchFuncTemplate = new \V8\FunctionTemplate($isolate, $fetch);
//Grab the JS runtime global object and inject our fetch function which actually calls into PHP
$context->GlobalObject()
->Set($context, new \V8\StringValue($isolate, 'fetch'), $fetchFuncTemplate->GetFunction($context));
https://github.com/pinepain/php-v8
https://simplywall.st