跳到导航

添加自定义代码

以 Markdown 格式查看

本页面介绍如何为您的 PHP SDK 添加自定义逻辑、方法和依赖项。

These steps cover adding a new custom file to the SDK. To preserve line-level edits to a generated file, use Replay instead.

添加自定义逻辑

开始添加自定义代码:

1

创建新文件并添加您的自定义逻辑

src/Helper.php
<?php
namespace YourNamespace;
class Helper
{
public static function myHelper(): void
{
echo "Hello World!";
}
}
2

将您的文件添加到 .fernignore

.fernignore
# Specify files that shouldn't be modified by Fern
src/Helper.php
3

使用辅助方法

Now your users can consume the helper function by importing it from the SDK.

<?php
use YourNamespace\Helper;
Helper::myHelper();

添加自定义 SDK 方法

Fern also allows you to add custom methods to the SDK itself (e.g. client.my_method() ) by inheriting the Fern generated client and then extending it.

1

更新 generators.yml 配置

将您的 Fern 生成的客户端命名为类似 BaseClient 的名称,以反映此客户端将被扩展。

generators.yml
- name: fern-php-sdk
version: 2.21.0
config:
clientName: BaseClient
2

导入并扩展生成的客户端

首先,导入 Fern 生成的基础客户端并扩展它。然后,添加您想要的任何方法。

src/MyClient.php
<?php
namespace YourNamespace;
class MyClient extends BaseClient
{
public function myHelper(): void
{
echo "Hello World!";
}
}
3

更新 .fernignore

MyClient.php 添加到 .fernignore

.fernignore
+ src/MyClient.php
4

使用方法

您的用户将构造扩展的客户端,而不是构造生成的客户端。

<?php
use YourNamespace\MyClient;
$client = new MyClient();

Now your users can consume the helper function by importing it from the SDK.

$client->myHelper();

添加自定义依赖项

要添加您的自定义代码所需的包,请使用 composerJson 配置选项更新您的 generators.yml

generators.yml
- name: fern-php-sdk
version: 2.21.0
config:
composerJson:
require:
guzzlehttp/guzzle: "^7.0"
require-dev:
phpunit/phpunit: "^10.0"