Ir al contenido principal

Cliente API de Playground

El objeto PlaygroundClient implementa la interfaz UniversalPHP. Todos los métodos de esa interfaz también están disponibles en Node.js e instancias PHP del mismo proceso (Playground ejecuta PHP en un web worker).

En términos generales, puedes usar el cliente para realizar tres tipos de operaciones:

  • Ejecutar código PHP
  • Personalizar PHP.ini
  • Gestionar archivos y directorios

Ejecutar código PHP

Los dos métodos que puedes usar para ejecutar código PHP son:

  • run() - ejecuta código PHP y devuelve la salida
  • request() - realiza una solicitud HTTP al sitio web

En Node.js, también puedes usar el método cli() para ejecutar PHP en modo CLI.

El método run()

El método 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().

Personalizar PHP.ini

El cliente API también te permite cambiar el archivo php.ini:

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

Gestionar archivos y directorios

El objeto client te proporciona una API de bajo nivel para gestionar archivos y directorios en el sistema de archivos PHP:

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');

Para obtener una lista completa de estos métodos, consulta la interfaz PlaygroundClient.

Enviar mensajes a JavaScript

Puedes pasar mensajes de PHP a JavaScript usando la función post_message_to_js(). Acepta un argumento:

  • $data (string) – Datos para pasar a JavaScript.

Por ejemplo, así es como enviarías un mensaje con un ID de publicación y un título codificado en JSON:

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:
const output = await php.runStream({
code: `<?php
post_message_to_js(
json_encode([
'post_id' => '15',
'post_title' => 'This is a blog post!'
])
);
`,
});

console.log(await output.stdoutText);
// You will see the following output in the console:
// { post_id: '15', post_title: 'This is a blog post!' }

El método cli()

En Node.js, también tienes acceso al método cli() que ejecuta PHP en modo CLI:

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

Una vez que el método cli() termina de ejecutarse, la instancia de PHP ya no es utilizable y debe descartarse. Esto se debe a que PHP internamente limpia todos los recursos y llama a exit().