Have you ever needed to use the functionality of a node.js package in your PHP project, but don't want to spend hours writing a wrapper? Well now you can.
Thanks to ReactPHP it was quite a simple script to get working.
Installation is easy via Composer:
$ composer require elevenways/doen
Or you can add it manually to your composer.json
file.
// 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();
Create a new Doen instance, which always creates a new Node.js instance too.
By default it'll use the node
binary, but this can be overridden with the node_path
option.
Require a node.js module and return a reference to it.
$libpath = $doen->require('path');
Execute an expression and return its value.
$promise = $doen->evaluate('1 + 1');
Execute a function with the supplied arguments and return its value.
$promise = $doen->evaluate('function(a, b) {return a * b}', [3, 2]);
Execute an expression or a function and return a reference to its value.
$libpath = $doen->evaluateToRef('require("path")');
Close the node.js process
$doen->close();
Get the actual value of the reference
$ref = $doen->evaluateToRef('1 + 1');
$ref->getValue(function($result) {
// Outputs: 2
echo $result;
});
Execute the callables when this reference resolves. It will not resolve to its value, but to its type for primitives and to its class for objects.
$ref = $doen->evaluateToRef('1 + 1');
$ref->then(function($type) {
// Outputs: "number"
echo $type;
});
$array = $doen->evaluateToRef('[]');
$ref->then(function($type) {
// Outputs: "Array"
echo $type;
});
Add a method to this instance on-the-fly
$ref = $doen->evaluateToRef('1 + 1');
$ref->__monkeyPatch('weird', function() {
return 'weird';
});
// Returns "weird"
$ref->weird();
Contributions are REALLY welcome. Please check the contributing guidelines for more details. Thanks!
- Jelle De Loecker - Follow me on Github (@skerit) and on Twitter (🐦@skeriten)
See also the list of contributors who participated in this project.
This project is licensed under the MIT License - see the LICENSE file for details.