PHP 与 Node.js 之间的桥梁

v0.1.2 2021-08-11 14:12 UTC

This package is auto-updated.

Last update: 2024-09-23 18:27:59 UTC


README

elevenways/doen

Build Status Codecov Coverage report Latest version on Packagist Project license
从 PHP 中异步调用 JavaScript 代码 由 Eleven Ways 用 ❤️ 编码。

简介

你是否需要在 PHP 项目中使用 node.js 包的功能,但又不想花几个小时编写包装器?现在你可以做到了。

得益于 ReactPHP,使其变得相当简单。

安装

通过 Composer 安装很简单

$ composer require elevenways/doen

或者你可以手动将其添加到你的 composer.json 文件中。

用法

简单的 require() 例子

// You will need an event loop instance.
// If this looks weird to you, you should lookup ReactPHP
$loop = \React\EventLoop\Factory::create();

// Now we can create a Doen instance
$doen = new \Elevenways\Doen\Doen($loop);

// Lets get our first, simple reference
// $libpath is now an \Elevenways\Doen\Reference instance
$libpath = $doen->evaluateToRef('require("path")');

// Even though the code is happening asynchronously, we can already act upon it
// This will return yet another \Elevenways\Doen\Reference instance
$str = $libpath->join('a', 'b', 'c');

// Now we can get the value
$str->getValue()->then(function ($value) {
    // This will print out a/b/c
    echo $value;
});

// This, again, is part of ReactPHP.
// It starts the event loop and will BLOCK the rest of the code!
$loop->run();

API

Doen

new Doen(\React\EventLoop\LoopInterface $loop, array $options = [])

创建一个新的 Doen 实例,这也会创建一个新的 Node.js 实例。

默认情况下,它将使用 node 二进制文件,但可以使用 node_path 选项来覆盖。

require(string $name) ⇒ \Elevenways\Doen\Reference

要求一个 node.js 模块并返回对其的引用。

$libpath = $doen->require('path');

evaluate(string $code) ⇒ \React\Promise\Promise

执行一个表达式并返回其值。

$promise = $doen->evaluate('1 + 1');

evaluateFunction(string $function, $args = []) ⇒ \React\Promise\Promise

使用提供的参数执行一个函数并返回其值。

$promise = $doen->evaluate('function(a, b) {return a * b}', [3, 2]);

evaluateToRef(string $code, $args = null) ⇒ \Elevenways\Doen\Reference

执行一个表达式或函数并返回其值的引用。

$libpath = $doen->evaluateToRef('require("path")');

close() ⇒ void

关闭 Node.js 进程

$doen->close();

引用

getValue(callable $on_fulfilled = null, callable $on_rejected = null) ⇒ \React\Promise\Promise

获取引用的实际值

$ref = $doen->evaluateToRef('1 + 1');
$ref->getValue(function($result) {
    // Outputs: 2
    echo $result;
});

then(callable $on_fulfilled = null, callable $on_rejected = null) ⇒ \React\Promise\Promise

当此引用解析时执行可调用函数。它将 不会 解析为其值,而是对于原始类型解析为其类型,对于对象解析为其类。

$ref = $doen->evaluateToRef('1 + 1');
$ref->then(function($type) {
    // Outputs: "number"
    echo $type;
});

$array = $doen->evaluateToRef('[]');
$ref->then(function($type) {
    // Outputs: "Array"
    echo $type;
});

__monkeyPatch($method_name, Closure $fnc) ⇒ void

在实例上动态添加方法

$ref = $doen->evaluateToRef('1 + 1');
$ref->__monkeyPatch('weird', function() {
    return 'weird';
});

// Returns "weird"
$ref->weird();

贡献

非常欢迎贡献。请查阅 贡献指南 了解更多详情。谢谢!

作者

还可以查看参与此项目的 贡献者列表

许可证

此项目遵循 MIT 许可证 - 详细信息请参阅 LICENSE 文件。