murdej/ts-link-php 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

murdej/ts-link-php

最新稳定版本:v1.7.1

Composer 安装命令:

composer require murdej/ts-link-php

包简介

A simple transparent link for calling php methods from typescript.

README 文档

README

What this thing can do. It simply connects PHP and typescript. Just write a class in PHP:

public function sayHello(string $name) : string
{
    return "Hello $name from PHP " . date('Y-m-d H:i:s') . ".";
}

and call in typescript:

const cl = new MyClassCL();
const value = await cl.sayHello("typescript");

How to use?

Install murdej/ts-link-php package with composer.

composer require murdej/ts-link-php

Create a class that will contain the methods you will use from js/ts. These methods must have the #[ClientMethod()] attribute from the namespace Murdej\TsLinkPhp\.

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') . ".";
    }
}

Create endpoint (in 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;

Generate js or ts code

$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://developer.mozilla.org/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);

The generation of js/ts must be started after creating or modifying the header of the method to be accessed from js/ts.

Then you can call PHP methods from js/ts.

<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>

统计信息

  • 总下载量: 54
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 1
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 1
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: Apache-2.0
  • 更新时间: 2021-12-07

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固