メインコンテンツへスキップ

Playground API クライアント

PlaygroundClient オブジェクトは UniversalPHP インターフェースを実装しています。このインターフェースのすべてのメソッドは、Node.js および同一プロセス内の PHP インスタンスでも利用可能です( Playground は Web Worker 内で PHP を実行します)。

大まかに言うと、クライアントを使用して 3 種類の操作を実行できます。

  • PHP コードの実行
  • PHP.iniのカスタマイズ
  • ファイルとディレクトリの管理

PHP コードの実行

PHP コードを実行するには、以下の 2 つの方法があります。

  • run() - PHP コードを実行し、その出力を返します。
  • request() - ウェブサイトに HTTP リクエストを送信します。

Node.js では、cli()メソッドを使用して PHP を CLI モードで実行することもできます。

run() メソッド

request() メソッド

Serves the request – either by serving a static file, or by dispatching it to the PHP runtime.

The request() method mode behaves like a web server and only works if the PHP was initialized with a requestHandler option (which the online version of WordPress Playground does by default).

In the request mode, you pass an object containing the request information (method, headers, body, etc.) and the path to the PHP file to run:

const php = PHP.load('7.4', {
requestHandler: {
documentRoot: "/www"
}
})
php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
const result = await php.request({
method: "GET",
headers: {
"Content-Type": "text/plain"
},
body: "Hello world!",
path: "/www/index.php"
});
// result.text === "Hello world!"

The request() method cannot be used in conjunction with cli().

PHP.iniのカスタマイズ

この API クライアントを使用すると、p​​hp.iniファイルを変更することもできます。

await setPhpIniEntries(client, {
display_errors: 'On',
error_reporting: 'E_ALL',
});

ファイルとディレクトリの管理

client オブジェクトは、PHP ファイルシステム内のファイルとディレクトリを管理するための低レベル API を提供します。

await client.mkdirTree('/wordpress/test');
// Create a new PHP file
await client.writeFile(
'/wordpress/test/index.php',
`<?php
echo "Hello, world!<br/>";
// List all the files in current directory
print_r(glob(__DIR__ . '/*'));
`
);
// Create files named 1, 2, and 3
await client.writeFile('/wordpress/test/1', '');
await client.writeFile('/wordpress/test/2', '');
await client.writeFile('/wordpress/test/3', '');
// Remove the file named 1
await client.unlink('/wordpress/test/1');
// Navigate to our PHP file
await client.goTo('/test/index.php');

これらのメソッドの完全なリストについては、PlaygroundClient インターフェースを参照してください。

JavaScript にメッセージを送信する

PHP から JavaScript にメッセージを渡すには、post_message_to_js() 関数を使用します。この関数は引数を 1 つ取ります。

  • $data (文字列) – JavaScript に渡すデータ。

例えば、JSON 形式でエンコードされた投稿 ID とタイトルを含むメッセージを送信するには、次のようにします。

import { PHP } from '@php-wasm/universal';
import { loadNodeRuntime } from '@php-wasm/node';

const php = new PHP(await loadNodeRuntime('8.3'));

php.onMessage(
// The data is always passed as a string
function (data: string) {
// Let's decode and log the data:
console.log(JSON.parse(data));
}
);

// Now that we have a listener in place, let's
// dispatch a message:
await php.runStream({
code: `<?php
post_message_to_js(
json_encode([
'post_id' => '15',
'post_title' => 'This is a blog post!'
])
);
`,
});

// You will see the following output in the console:
// { post_id: '15', post_title: 'This is a blog post!' }

cli() メソッド

Node.js では、PHP を CLI モードで実行する cli() メソッドにもアクセスできます。

// Run PHP in a CLI mode
client.cli(['-r', 'echo "Hello, world!";']);
// Outputs "Hello, world!"

cli() メソッドの実行が完了すると、PHP インスタンスは使用できなくなるため、破棄する必要があります。これは、PHP が内部的にすべてのリソースを解放し、exit()を呼び出すためです。