生命周期钩子
什么是生命周期钩子?
钩子让你的插件在构建过程中的特定点运行代码。需要在编译前下载 ML 模型?将资源复制到正确的平台目录?运行验证?钩子处理这些场景。
声明式 vs 编程式资源
对于简单的文件复制,使用清单中的声明式 assets 字段。仅当你需要动态行为(如下载文件、解压档案或条件复制)时才使用 copy_assets 钩子。
可用钩子
| 钩子 | 运行时机 |
|---|---|
pre_compile | 原生代码编译之前 |
post_compile | 编译之后,构建之前 |
copy_assets | 将资源复制到原生项目时(在声明式资源复制之后运行) |
post_build | 成功构建之后 |
创建钩子命令
使用脚手架工具生成钩子命令:
shell
php artisan native:plugin:make-hook这将引导你选择插件和要创建的钩子。它会生成命令类,更新你的清单,并在服务提供者中注册命令。
钩子命令结构
钩子命令继承 NativePluginHookCommand:
php
use Native\Mobile\Plugins\Commands\NativePluginHookCommand;
class CopyAssetsCommand extends NativePluginHookCommand
{
protected $signature = 'nativephp:my-plugin:copy-assets';
public function handle(): int
{
if ($this->isAndroid()) {
$this->copyToAndroidAssets('models/model.tflite', 'models/model.tflite');
}
if ($this->isIos()) {
$this->copyToIosBundle('models/model.mlmodel', 'models/model.mlmodel');
}
return self::SUCCESS;
}
}可用助手
基础命令为常见任务提供助手:
平台检测:
$this->platform()— 返回'ios'或'android'$this->isIos()、$this->isAndroid()— 布尔检查
路径:
$this->buildPath()— 正在构建的原生项目路径$this->pluginPath()— 你的插件包路径$this->appId()— 应用的 bundle ID(例如com.example.app)
文件操作:
$this->copyToAndroidAssets($src, $dest)— 复制到 Android assets$this->copyToIosBundle($src, $dest)— 复制到 iOS bundle$this->downloadIfMissing($url, $dest)— 如果文件不存在则下载$this->unzip($zipPath, $extractTo)— 解压 zip 文件
在清单中声明钩子
将钩子添加到你的 nativephp.json:
json
{
"hooks": {
"copy_assets": "nativephp:my-plugin:copy-assets",
"pre_compile": "nativephp:my-plugin:pre-compile"
}
}值是你的 Artisan 命令签名。
示例:下载 ML 模型
php
public function handle(): int
{
$modelPath = $this->pluginPath() . '/resources/models/model.tflite';
// 如果本地没有缓存则下载
$this->downloadIfMissing(
'https://example.com/models/v2/model.tflite',
$modelPath
);
// 复制到适当的平台位置
if ($this->isAndroid()) {
$this->copyToAndroidAssets('models/model.tflite', 'models/model.tflite');
$this->info('Model copied to Android assets');
}
if ($this->isIos()) {
$this->copyToIosBundle('models/model.tflite', 'models/model.tflite');
$this->info('Model copied to iOS bundle');
}
return self::SUCCESS;
}提示
钩子作为普通 Artisan 命令运行。你可以完全访问 Laravel 的控制台助手——$this->info()、$this->warn()、进度条等。
官方插件和开发工具包
浏览现成的插件或获取开发工具包来构建你自己的。 访问 NativePHP 插件市场 →