diff --git a/packages/docs/site/docs/developers/06-apis/javascript-api/03-playground-api-client.md b/packages/docs/site/docs/developers/06-apis/javascript-api/03-playground-api-client.md index 5f7c625841..2c8bea57cb 100644 --- a/packages/docs/site/docs/developers/06-apis/javascript-api/03-playground-api-client.md +++ b/packages/docs/site/docs/developers/06-apis/javascript-api/03-playground-api-client.md @@ -77,8 +77,11 @@ You can pass messages from PHP to JavaScript using the `post_message_to_js()` fu For example, here's how you would send a message with a JSON-encoded post ID and title: -```ts -const php = await PHP.load('8.0'); +```TypeScript +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 @@ -90,14 +93,14 @@ php.onMessage( // Now that we have a listener in place, let's // dispatch a message: -await php.run({ +await php.runStream({ code: ` '15', 'post_title' => 'This is a blog post!' ]) - )); + ); `, }); diff --git a/packages/docs/site/i18n/es/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md b/packages/docs/site/i18n/es/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md new file mode 100644 index 0000000000..fbd3174dd6 --- /dev/null +++ b/packages/docs/site/i18n/es/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md @@ -0,0 +1,207 @@ +--- +slug: /developers/apis/javascript-api/playground-api-client +--- + + + +# 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()`](#the-run-method) - ejecuta código PHP y devuelve la salida +- [`request()`](#the-request-method) - realiza una solicitud HTTP al sitio web + + + +En Node.js, también puedes usar el método [`cli()`](#the-cli-method) para ejecutar PHP en modo CLI. + + + +### El método `run()` + +import TSDocstring from '@site/src/components/TSDocstring'; + + + + + +### El método `request()` + + + + + +## Personalizar `PHP.ini` + + + +El cliente API también te permite cambiar el archivo `php.ini`: + +```ts +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: + +```ts +await client.mkdirTree('/wordpress/test'); +// Create a new PHP file +await client.writeFile( + '/wordpress/test/index.php', + `"; + // 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: + +```TypeScript +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: ` '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: + +```ts +// 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()`. diff --git a/packages/docs/site/i18n/fr/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md b/packages/docs/site/i18n/fr/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md new file mode 100644 index 0000000000..ce1ee09d96 --- /dev/null +++ b/packages/docs/site/i18n/fr/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md @@ -0,0 +1,206 @@ +--- +slug: /developers/apis/javascript-api/playground-api-client +--- + + + +# Client API Playground + + + +L'objet `PlaygroundClient` implémente l'interface `UniversalPHP`. Toutes les méthodes de cette interface sont également disponibles dans Node.js et les instances PHP du même processus (Playground exécute PHP dans un web worker). + + + +De manière générale, vous pouvez utiliser le client pour effectuer trois types d'opérations : + +- Exécuter du code PHP +- Personnaliser `PHP.ini` +- Gérer les fichiers et dossiers + + + +## Exécuter du code PHP + + + +Les deux méthodes que vous pouvez utiliser pour exécuter du code PHP sont : + +- [`run()`](#the-run-method) - exécute du code PHP et renvoie la résultat +- [`request()`](#the-request-method) - effectue une requête HTTP au site web + + + +Dans Node.js, vous pouvez également utiliser la méthode [`cli()`](#the-cli-method) pour exécuter PHP en mode CLI. + + + +### La méthode `run()` + +import TSDocstring from '@site/src/components/TSDocstring'; + + + + + +### La méthode `request()` + + + + + +## Personnaliser `PHP.ini` + + + +Le client API vous permet également de modifier le fichier `php.ini` : + +```ts +await setPhpIniEntries(client, { + display_errors: 'On', + error_reporting: 'E_ALL', +}); +``` + + + +## Gérer les fichiers et dossiers + + + +L'objet `client` vous fournit une API de bas niveau pour gérer les fichiers et dossiers dans le système de fichiers PHP : + +```ts +await client.mkdirTree('/wordpress/test'); +// Create a new PHP file +await client.writeFile( + '/wordpress/test/index.php', + `"; + // 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'); +``` + + + +Pour une liste complète de ces méthodes, consultez l'interface `PlaygroundClient`. + + + +## Envoyer des messages à JavaScript + + + +Vous pouvez transmettre des messages de PHP à JavaScript en utilisant la fonction `post_message_to_js()`. Elle accepte un argument : + +- `$data` (string) – Données à transmettre à JavaScript. + + + +Par exemple, voici comment envoyer un message avec un ID de publication et un titre encodés en JSON : + +```TypeScript +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: ` '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!' } +``` + + + +## La méthode `cli()` + + + +Dans Node.js, vous avez également accès à la méthode `cli()` qui exécute PHP en mode CLI : + +```ts +// Run PHP in a CLI mode +client.cli(['-r', 'echo "Hello, world!";']); +// Outputs "Hello, world!" +``` + + + +Une fois que la méthode `cli()` a terminé son exécution, l'instance PHP n'est plus utilisable et doit être supprimée. Cela est dû au fait que PHP nettoie en interne toutes les ressources et appelle `exit()`. diff --git a/packages/docs/site/i18n/pt-BR/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md b/packages/docs/site/i18n/pt-BR/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md index d7cacf09dc..01e8dabf4b 100644 --- a/packages/docs/site/i18n/pt-BR/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md +++ b/packages/docs/site/i18n/pt-BR/docusaurus-plugin-content-docs/current/developers/06-apis/javascript-api/03-playground-api-client.md @@ -111,8 +111,11 @@ Você pode enviar mensagens do PHP para o JavaScript usando a função `post_mes Por exemplo, veja como enviar uma mensagem com um ID e título de post codificados em JSON: -```ts -const php = await PHP.load('8.0'); +```TypeScript +import { PHP } from '@php-wasm/universal'; +import { loadNodeRuntime } from '@php-wasm/node'; + +const php = new PHP(await loadNodeRuntime('8.3')); php.onMessage( // Os dados são sempre passados como string @@ -123,8 +126,8 @@ php.onMessage( ); // Agora que temos um listener, vamos -enviar uma mensagem: -await php.run({ +//enviar uma mensagem: +await php.runStream({ code: `', }); -console.log(response.text); +console.log(await output.stdoutText); ``` ## Attribution diff --git a/packages/php-wasm/web/README.md b/packages/php-wasm/web/README.md index 02f37d0d7f..2641c003a2 100644 --- a/packages/php-wasm/web/README.md +++ b/packages/php-wasm/web/README.md @@ -5,29 +5,42 @@ This package ships WebAssembly PHP binaries and the JavaScript API optimized for Here's how to use it: ```js -import { PHP } from '@php-wasm/web'; +import { PHP, PHPRequestHandler } from '@php-wasm/universal'; +import { loadWebRuntime } from '@php-wasm/web'; -// PHP.load() calls import('php.wasm') internally +// loadWebRuntime() calls import('php.wasm') and import('icudt74l.dat') internally. // Your bundler must resolve import('php.wasm') as a static file URL. // If you use Webpack, you can use the file-loader to do so. -const php = await PHP.load('8.0', { - requestHandler: { - documentRoot: '/www', - }, +const php = new PHP(await loadWebRuntime('8.3')); + +let response; + +php.writeFile('/test.php', ``); + +// Run a script directly: +response = await php.runStream({ + scriptPath: '/test.php', }); -// Create and run a script directly -php.mkdirTree('/www'); +console.log(await response.stdoutText); +// You will see the following output in the browser console: +// Hello, World! + +php.mkdir('/www'); php.writeFile('/www/index.php', ``); -await php.run({ scriptPath: './index.php' }); // Or use the familiar HTTP concepts: -const response = await php.request({ +const handler = new PHPRequestHandler({ phpFactory: async () => php }); + +response = await handler.request({ method: 'POST', - url: '/index.php', - data: { name: 'John' }, + url: 'index.php', + body: { name: 'John' }, }); + console.log(response.text); +// You will see the following output in the browser console: +// Hello John ``` ## Attribution