nacmartin/phpexecjs

从PHP运行JavaScript代码

v3.1.0 2021-12-23 10:43 UTC

README

PhpExecJS 允许您从PHP运行JavaScript代码。

简例

print_r($phpexecjs->evalJs("'red yellow blue'.split(' ')"));

将打印

Array
(
    [0] => red
    [1] => yellow
    [2] => blue
)

Build Status Latest Stable Version Latest Unstable Version License

安装

composer require nacmartin/phpexecjs

示例程序

用法

<?php
    require __DIR__ . '/../vendor/autoload.php';
    
    use Nacmartin\PhpExecJs\PhpExecJs;
    
    $phpexecjs = new PhpExecJs();
    
    print_r($phpexecjs->evalJs("'red yellow blue'.split(' ')"));

将打印

Array
(
    [0] => red
    [1] => yellow
    [2] => blue
)

使用上下文

您可以为您的eval'd代码设置一个上下文,例如库等。这通常由ReactBundle用于在服务器端渲染React。

例如,我们可以使用此功能编译CoffeeScript

    $phpexecjs->createContextFromFile("https://coffeescript.node.org.cn/extras/coffee-script.js");
    print_r($phpexecjs->call("CoffeeScript.compile", ["square = (x) -> x * x", ['bare' => true]]));


That will print:

      var square;
    
      square = function(x) {
        return x * x;
      };

您可以将此示例扩展到使用此函数作为上下文等功能

    $square = $phpexecjs->call("CoffeeScript.compile", ["square = (x) -> x * x", ['bare' => true]]);
    $phpexecjs->createContext($square);
    print_r($phpexecjs->evalJs('square(3)'));

这将打印 9

这可以用于例如使用CoffeeScript或编译JavaScript模板语言中的模板。

它是如何工作的

当您运行evalJs时,代码将插入到一个小的包装器中,用于运行JavaScript的eval()对您的代码进行检查,以便进行错误处理。

如果您设置了上下文,代码将插入到JavaScript中对eval()的调用之前,并且如果您安装了V8Js扩展,它将预先编译它。

支持的运行时

默认情况下,PhPExecjs将自动检测最佳可用运行时。目前支持的运行时包括

建议安装V8Js,但在生产中安装它,同时仍然可以在开发期间使用PhpExecJs调用node作为子进程,这样您就不需要安装扩展。

添加外部运行时

如果您有一个外部运行器(例如,Spidermonkey),并且想使用它,只需将其传递给构造函数即可

    $myRuntime = new ExternalRuntime('My runtime name', 'my_command');
    $phpExecJs = new PhpExecJs($myRuntime);

通过运行时进行贡献

我们希望支持更多的运行时(例如,Duktape)。如果您想为运行时做出贡献,这非常简单。您只需实现src/Runtimes/RuntimeInterface。请查看src/Runtimes目录以获取示例。

为什么我不能使用某些函数,如setTimeout

PhpExecJs为JavaScript运行时提供了一个公共接口,因此它只能运行与解释器无关的代码。因此,某些功能被禁用。特别是,计时器函数被禁用,因为并非所有运行时都保证完整的JavaScript事件循环。如果您想使用这些功能之一,请直接使用node.js而不是这个高级库。

globalmoduleexportsrequireconsolesetTimeoutsetIntervalclearTimeoutclearIntervalsetImmediateclearImmediate

致谢

此库受ExecJs启发,这是一个Ruby库。

用于管理进程和临时文件的部分代码已从Snappy库中改编。