murdej / ts-link-php
一个简单的透明链接,用于从 TypeScript 调用 PHP 方法。
v1.4.0
2024-09-18 12:04 UTC
Requires
- php: >=8.0
- nette/utils: ^3.0 || ^4.0
This package is auto-updated.
Last update: 2024-09-18 12:21:43 UTC
README
这个工具能做什么。它简单地将 PHP 和 TypeScript 连接起来。只需在 PHP 中编写一个类
public function sayHello(string $name) : string { return "Hello $name from PHP " . date('Y-m-d H:i:s') . "."; }
并在 TypeScript 中调用它
const cl = new MyClassCL(); const value = await cl.sayHello("typescript");
如何使用?
使用 composer 安装 murdej/ts-link-php
包。
composer require murdej/ts-link-php
创建一个包含您将从 js/ts 中使用的方法的类。这些方法必须具有来自命名空间 Murdej\TsLinkPhp\
的 #[ClientMethod()]
属性。
use Murdej\TsLinkPhp\ClientMethod; class MyClassCL { #[ClientMethod()] public function sayHello(string $name) : string { return "Hello $name from PHP " . date('Y-m-d H:i:s') . "."; } }
创建端点(在 endpoint.php
中)
// Create instance of your service $service = new MyClassCL(); // Create an instance of TsLink and pass your service to the constructor. $tl = new TsLink($service); // Get raw post content $rawPost = file_get_contents('php://input'); // Call processRequest and pass contents, $response = $tl->processRequest($rawPost); // Result sent as json header('Content-type: ' . $response->getContentType()); echo $response;
生成 js 或 ts 代码
$tsg = new TsCodeGenerator(); // Add a PHP class, optionally also the endpoint address. This step can be repeated. $tsg->add(MyClassCL::class, './endpoint.php'); // Export format, can be ts or js. Default is ts $tsg->format = "js"; // Enable or disable js modules (https://mdn.org.cn/en-US/docs/Web/JavaScript/Guide/Modules) $tsg->useExport = false; // Create and save ts/js sources $source = $tsg->generateCode(); file_put_contents('./tslClasses.js', $source);
在创建或修改从 js/ts 访问的方法的头部之后,必须开始生成 js/ts 代码。
然后您就可以从 js/ts 中调用 PHP 方法了。
<h1 id="message"></h1> <script src="tslClasses.js"></script> <script> const myClass = new MyClassCL(); (async () => { const res = await myClass.sayHello("TypeScript"); document.getElementById("message").innerText = res; })(); </script>