I have started using v8js with php for a while now but the documentation is really thin.
One thing that is not explained is Extensions.
It is possible to registerExtension but it is not explained in detail how these behave or whats their purpose or benefits.
Can anyone provide a good description or link to a documentation that explains Extensions?
Thanks to everyone for taking time to read and answer :-)
Original Answer
My original answer indicated that the extension was called every time executeString was.
Corrected answer
An extension is a bit of code that is executed before the first executeString call for a given V8Js instance.
Extension can be global to all V8Js instances or local to a specific instance.
I have experimentally determined that this isn't always very reliable. If you frantically refresh a page, you may not always see the extension get run... This is probably why this is beta quality software.
Here are two examples that I whipped up
Global Extension Example
Code
V8Js::registerExtension('say_hi', 'print("hey from extension! "); var said_hi=true;', array(), true);
$v8 = new V8Js();
$v8->executeString('print("hello from regular code!")', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
Output
hey from extension! hello from regular code! extension already said hi
Non-Global Example
Code
V8Js::registerExtension('say_hi', 'print("hey from non global extension! "); var said_hi=true;');
$v8 = new V8Js('PHP', array(), array('say_hi'));
$v8->executeString('print("hello from regular code!");', 'test.php');
$v8->executeString('if (said_hi) { print(" extension already said hi"); }');
Output
hey from non global extension! hello from regular code! extension already said hi
Related
I'm following the instructions from BryanH's answer here: gettext() equivalent in Intl library? and trying to implement localization (translation) with php-intl, but I keep getting the same problem this person had: ResourceBundle returns NULL without any errors being raised
He mentions he created the dat files with a tool (which I cannot figure out how to work) while the person in the former answer simply appears to be using txt files with a .res extension.
How do I properly implement localization with php-intl and ResourceBundle, and what am I doing wrong?
The goal is to have various data files with different languages so I can do something similar to
$t = new Translator();
$t->setResource(new \ResourceBundle('es', 'locales_folder/'));
$t->echo("somestring"); // "el stringo"
..much like the person in the first answer had. Also, the aim is to have easily editable files, so I can give them to translators for fixes, updates, and so on. I realize I could easily do this with custom solution through a simple text file which gets parsed and saved into memcache on first request, where it then persists and gets served from without having to re-read the .dat files, but I'd rather take the suggested route here.
Edit: Just to get it out there - I implemented the same thing with gettext successfully and it was dead easy - save for one bug that persists across linux systems (http://www.php.net/manual/en/book.gettext.php#91187) - but I'd like to rely on the more modern and all-inclusive intl extension if possible.
I can provide a solution to your question on how to create and use .res files for the intl PHP extension, however I have no experience with speed and use in production systems, you will have to see for yourself if this can be a replacement for gettext.
In my opinion a great benefit of gettext are additional tools such as xgettext which can extract strings to be translated. Still, using resources might be more useful in your use-case.
To generate a .res file you need to use the program genrb which is bundled with ICU. (for example when installing ICU on OSX using brew install icu4c (see this tutorial) you can find the tool at /usr/local/Cellar/icu4c/*/bin/genrb (replace * with the version number))
Next you prepare a file for each locale. Let's do this for two languages in this example, German and Spanish.
$ cat de.txt
de {
hello { "Hallo" }
}
$ cat es.txt
es {
hello { "Hola" }
}
$ genrb *.txt
genrb number of files: 2
You now have 2 additional files de.res and es.res, which you can now access in PHP
<?php
foreach (array("de", "es") as $locale) {
$r = ResourceBundle::create($locale, __DIR__);
echo $r["hello"], "\n";
}
which will output
Hallo
Hola
So in essence, you can hand those *.txt files to your translaters and prepare them for PHP using genrb.
Finally, a small example for the class you were trying to write:
<?php
class Translator {
private $resourceBundle = null;
public function __construct(\ResourceBundle $r) {
$this->resourceBundle = $r;
}
public function __get($string) {
return $this->resourceBundle[$string];
}
}
$t = new Translator(new \ResourceBundle('es', __DIR__));
echo $t->hello;
I'm not entirely sure the wording for the title is correct, but what I'm attempting to do is run and execute PHP files from within the Lift framework.
I'm not after any url queries to a PHP file residing on a server, more interested in somehow getting the PHP runtime working through my Scala/Lift app.
Use case: I have my app packaged into a .war file, I host this via a cloud provider. I upload code snippets to said app which then runs the php file and does whatever necessary.
I've seen various posts regarding Bianca but am hoping to keep this setup light and require only the PHP binary itself and a little code to get it flying.
Thanks in advance, please let me know if you need me to elaborate :)
“Never say never, because limits, like fears, are often just an
illusion.”
― Michael Jordan
What you really need is an open source (GPL), embeddable, full PHP 5 implementation, written entirely in Java!
Caucho's Quercus PHP Java runtime is just that, and it will let you run PHP within a Java app without external libraries or native code.
Below is a Quercus-PHP-in-Java code sample I found in this answer
import javax.script.ScriptEngine;
import com.caucho.quercus.script.QuercusScriptEngineFactory;
QuercusScriptEngineFactory factory = new QuercusScriptEngineFactory();
ScriptEngine engine = factory.getScriptEngine();
String phpCode = "<?php $foo = strlen('abc'); print $foo; return 'yikes'; ?>"; //PHP Code as String
Object o = engine.eval(phpCode);
System.out.println(o);
It should be little effort to convert this code to idiomatic Scala. Obviously, the 'phpCode' variable could be constructed from external PHP file contents etc.
Let us know how you get on ;-)
That's a bit of an odd requirement, but if it's what you need to do, you can use a ProcessBuilder to execute and interact with your PHP script from the command line.
I have a GTFS protocol buffer message (VehiclePosition.pb), and the corresponding protocol format (gtfs-realtime.proto), I would like to read the message in PHP alone (is that even possible?).
I looked at Google's python tutorial https://developers.google.com/protocol-buffers/docs/pythontutorial and encoding documentation https://developers.google.com/protocol-buffers/docs/encoding and https://github.com/maxious/ACTBus-ui/tree/master/lib/Protobuf-PHP, but I am having a really hard time conceptualizing what is going on. I think I understand that gtfs-realtime.php is a compiled instruction set of the encoding defined in gtfs-realtime.proto (please correct me if I am wrong), but I have no clue how to get it to decode VehiclePosition.pb. Also, what are the dependencies of gtfs-realtime.php (or the python equivalent for that matter)? Is there anything else I have to compile myself or anything that is not a simple php script if all I want to do is read VehiclePosition.pb?
Thanks.
edmonscommerce and Julian are on the right track.
However, I've gone down the same path and I've found that the PHP implementation of Protocol Buffers is cumbersome (especially in the case of NYCT's MTA feed).
Alternative Method (Command Line + JSON):
If you're comfortable with command line tools and JSON, I wrote a standalone tool that converts GTFS-realtime into simple JSON: https://github.com/harrytruong/gtfs_realtime_json
Just download (no install), and run: gtfs_realtime_json <feed_url>
Here's a sample JSON output.
To use this in PHP, just put gtfs_realtime_json in the same directory as your scripts, and run the following:
<?php
$json = exec('./gtfs_realtime_json "http://developer.mbta.com/lib/GTRTFS/Alerts/VehiclePositions.pb"');
$feed = json_decode($json, TRUE);
var_dump($feed);
You can use the official tool: https://developers.google.com/transit/gtfs-realtime/code-samples#php
It was released very recently. I've been using it for a few days and works like a charm.
I would assume something along the lines of this snippet:
<?php
require_once 'DrSlump\Protobuf.php';
use DrSlump\Protobuf;
$data = file_get_contents('data.pb');
$person = new Tutorial\Person($data);
echo $person->getName();
as taken from the man page: http://drslump.github.io/Protobuf-PHP/protobuf-php.3.html
Before that step, I think you need to generate your PHP classes using the CLI tool as described here: http://drslump.github.io/Protobuf-PHP/protoc-gen-php.1.html
so something along the lines of:
protoc-gen-php gtfs-realtime.proto
Sorry Harry Truong, I tried your executable but it returns always NULL.
What I am doing wrong?
Edit: The problem is that I have no permission to execute in my server. Thanks for your executable.
Creating a search function on my site using php/sql, simple enough - just using a SELECT ALL query on the database using the LIKE clause and echoing the result on the page. My question is, how can I add spelling suggestions in case the user mistyped their search query. Mysql doesn't return anything unless the search term matches exactly with the database content, e.g. "Dofs" will not return "Dogs". So how can spelling suggestions be added?
Thanks.
Following you will find an excellent article by Peter Norvig on how to write a spell checker:
http://www.norvig.com/spell-correct.html
and the following two links are implementations in PHP of the code found in the article:
http://www.phpclasses.org/browse/package/4859.html
http://soundofemotion.com/spellcorrect.txt
Hope this helps.
What about PHP's pspell extension?
<?php
$pspell_link = pspell_new("en");
if (!pspell_check($pspell_link, "dofs")) {
$suggestions = pspell_suggest($pspell_link, "dofs");
foreach ($suggestions as $suggestion) {
echo "Possible spelling: $suggestion<br />";
}
}
?>
This PHP extension requires that you have aspell libraries installed.
You need to check out something like the following:
http://phpir.com/spelling-correction
You will need a dictionary and the levenstien function basically.
in addition to Joe's excellent solution, you can make a soap call to provide alternate spellings (based on a search engine's language corpus)
Yahoo Spelling Suggestion:
http://developer.yahoo.com/search/web/V1/spellingSuggestion.html
Google spelling request:
http://code.google.com/apis/soapsearch/reference.html#1_3
Coming here in March 2020, then https://tigitz.github.io/php-spellchecker/ is worth looking at.
From the docs:
PHP-Spellchecker is a spellchecker abstraction library for PHP. By providing a unified interface for many different spellcheckers, you’re able to swap out spellcheckers without extensive rewrites.
Using PHP-Spellchecker can eliminate vendor-lock in, reduce technical debt, and improve the testability of your code.
I'm not going to lie. I'm not all the familiar with Windows and COM objects. That's why i'm here. First of all is it possible to access a DLL from within a PHP script running out of Apache? In my journey around the internets i believe that i have 2 options:
compile the dll as an extension for PHP. (i didn't make this dll)
access the DLL as a COM object which is sort of what it's designed for anyways.
So i'm taking the COM approach.
try{
$com = new COM('WHAT_GOES_HERE');
} catch(Exception $e){
echo 'error: ' . $e->getMessage(), "\n";
}
How do i go about finding out what would go into the initialization string? is there a com viewer type program i could/should be using to find this out? the documentation associated with this DLL doesn't seem to specify what strings i should be using to initialize but gets very in-depth into what streams are available, and all sorts of fun stuff. just gotta past this initial hump. Please help!
WHAT_GOES_HERE is the ProgID, Class ID or Moniker registered on the Operating System.
Each of these can change for the same DLL registered on different machines. There are several ways to find what's the ProgID/CLSID/Moniker of a registered dll. You can search the web for "dll debugger", "dll export", "dll inspect" and you'll see several solutions, and also ways to show what functions the dll export so you can use them.
The easiest way, you can just register the dll with Regsvr32.exe and search Window's register with regedit.exe for the dll's name, you might need to search several times until you find the key under \HKEY_CLASSES_ROOT\, which is the ProgID.
The command dcomcnfg.exe shows a lot of information about COM objects.
If you have Visual Studio, the OLE/COM Object Viewer (oleview.exe) might be useful.
You can run dll functions (from dlls which are not php extensions) with winbinder.
http://winbinder.org/
Using it is simple. You have to download php_winbinder.dll and include it in php.ini as an extension.
In the php script you have to use something similar:
function callDll($func, $param = "")
{
static $dll = null;
static $funcAddr = null;
if ($dll === null)
{
$dll = wb_load_library(<DLL PATH AND FILENAME>);
}
$funcAddr = wb_get_function_address($func, $dll);
if ($param != "")
{
return wb_call_function($funcAddr,array(mb_convert_encoding($param,"UTF-16LE")));
}
else
{
return wb_call_function($funcAddr);
}
}
You can simply develop a wrapper around your main dll and use this wrapper as an extension in your PHP. Some free tools like SWIG can generate this wrapper for you automatically by getting the header of your dll functions. I myself use this approach and it was easy and reliable.
With PHP>=7.4.0's new FFI/Foreign Function Interface (which didn't exist yet when this question was posted), this is now easier than ever before! For example, to call the GetCurrentProcessId(); function from kernel32.dll:
<?php
declare(strict_types=1);
$ffi = FFI::cdef(
'unsigned long GetCurrentProcessId(void);',
"C:\\windows\\system32\\kernel32.dll"
);
var_dump($ffi->GetCurrentProcessId());
outputs
C:\PHP>php test.php
int(24200)
:)