
欢迎来到sharpapi laravel 集成指南!该存储库提供了有关如何将 sharpapi 集成到下一个 laravel ai 应用程序中的全面的分步教程。无论您是希望通过**人工智能支持的功能**还是自动化工作流程来增强您的应用程序,本指南都将引导您完成从身份验证到进行 api 调用和处理响应的整个过程。
文章也作为 github 存储库发布在 https://github.com/sharpapi/laravel-ai-integration-guide。
开始之前,请确保您已满足以下要求:
如果你已经有 laravel 项目,可以跳过此步骤。否则,请按照以下说明创建一个新的 laravel 项目。
composer create-project --prefer-dist laravel/laravel laravel-ai-integration-guide
cd laravel-ai-integration-guide
php artisan serve
可以通过 http://localhost:8000 访问该应用程序。
要与 sharpapi 交互,您需要安装 sharpapi php 客户端库。
需要通过 composer 安装 sharpapi 包
composer require sharpapi/sharpapi-laravel-client php artisan vendor:publish --tag=sharpapi-laravel-client
在环境变量中存储 api 密钥等敏感信息是最佳实践。 laravel 使用 .env 文件进行特定于环境的配置。
位于 laravel 项目的根目录中。
sharp_api_key=your_actual_sharpapi_api_key_here
注意:将此处的 your_actual_sharpapi_api_key_key_替换为您实际的 sharpapi api 密钥。
laravel 提供了 env 辅助函数来访问环境变量。
$apikey = env('sharp_api_key');
需要进行身份验证才能安全地与 sharpapi 端点交互。
创建服务或直接在控制器中使用它。
<?php
namespace app\services;
use sharpapi\sharpapiservice;
class sharpapiclient
{
protected $client;
public function __construct()
{
$this->client = new sharpapiservice(env('sharp_api_key'));
}
public function getclient()
{
return $this->client;
}
}
这允许您在需要的地方注入服务。
<?php
namespace app\providers;
use illuminate\support\serviceprovider;
use app\services\sharpapiclient;
class appserviceprovider extends serviceprovider
{
public function register()
{
$this->app->singleton(sharpapiclient::class, function ($app) {
return new sharpapiclient();
});
}
public function boot()
{
//
}
}
<?php
namespace app\http\controllers;
use illuminate\http\request;
use app\services\sharpapiclient;
class sharpapicontroller extends controller
{
protected $sharpapi;
public function __construct(sharpapiclient $sharpapi)
{
$this->sharpapi = $sharpapi->getclient();
}
public function ping()
{
$response = $this->sharpapi->ping();
return response()->json($response);
}
}
将路由添加到routes/web.php或routes/api.php:
use app\http\controllers\sharpapicontroller;
route::get('/sharpapi/ping', [sharpapicontroller::class, 'ping']);
经过身份验证后,您可以开始对各种 sharpapi 端点进行 api 调用。以下是如何与不同端点交互的示例。
<?php
namespace app\http\controllers;
use illuminate\http\request;
use app\services\sharpapiclient;
use sharpapi\dto\jobdescriptionparameters;
class sharpapicontroller extends controller
{
protected $sharpapi;
public function __construct(sharpapiclient $sharpapi)
{
$this->sharpapi = $sharpapi->getclient();
}
public function generatejobdescription()
{
$jobdescriptionparams = new jobdescriptionparameters(
"software engineer",
"tech corp",
"5 years",
"bachelor's degree in computer science",
"full-time",
[
"develop software applications",
"collaborate with cross-functional teams",
"participate in agile development processes"
],
[
"proficiency in php and laravel",
"experience with restful apis",
"strong problem-solving skills"
],
"usa",
true, // isremote
true, // hasbenefits
"enthusiastic",
"category c driving license",
"english"
);
$statusurl = $this->sharpapi->generatejobdescription($jobdescriptionparams);
$resultjob = $this->sharpapi->fetchresults($statusurl);
return response()->json($resultjob->getresultjson());
}
}
route::get('/sharpapi/generate-job-description', [sharpapicontroller::class, 'generatejobdescription']);
访问 http://localhost:8000/sharpapi/generate-job-description 查看生成的职位描述。
sharpapi 响应通常封装在作业对象中。要有效处理这些响应:
{
"id": "uuid",
"type": "jobtype",
"status": "completed",
"result": {
// result data
}
}
使用提供的方法访问结果数据。
$resultjob = $this->sharpapi->fetchresults($statusurl); $resultdata = $resultjob->getresultobject(); // as a php object // or $resultjson = $resultjob->getresultjson(); // as a json string
public function generatejobdescription()
{
// ... (initialize and make api call)
if ($resultjob->getstatus() === 'completed') {
$resultdata = $resultjob->getresultobject();
// process the result data as needed
return response()->json($resultdata);
} else {
return response()->json(['message' => 'job not completed yet.'], 202);
}
}
正确的错误处理可确保您的应用程序能够妥善处理 api 交互期间出现的问题。
将 api 调用包装在 try-catch 块中以处理异常。
public function generatejobdescription()
{
try {
// ... (initialize and make api call)
$resultjob = $this->sharpapi->fetchresults($statusurl);
return response()->json($resultjob->getresultjson());
} catch (\exception $e) {
return response()->json([
'error' => 'an error occurred while generating the job description.',
'message' => $e->getmessage()
], 500);
}
}
检查作业的状态,并针对不同的状态进行相应的处理。
if ($resultjob->getstatus() === 'completed') {
// handle success
} elseif ($resultjob->getstatus() === 'failed') {
// handle failure
$error = $resultjob->getresultobject()->error;
return response()->json(['error' => $error], 400);
} else {
// handle other statuses (e.g., pending, in progress)
return response()->json(['message' => 'job is still in progress.'], 202);
}
测试对于确保您与 sharpapi 的集成按预期工作至关重要。
使用 laravel 的内置测试工具为 sharpapi 集成编写单元测试。
<?php
namespace tests\feature;
use tests\testcase;
use app\services\sharpapiclient;
use sharpapi\dto\jobdescriptionparameters;
class sharpapitest extends testcase
{
protected $sharpapi;
protected function setup(): void
{
parent::setup();
$this->sharpapi = new sharpapiclient();
}
public function testping()
{
$response = $this->sharpapi->ping();
$this->assertequals('ok', $response['status']);
}
public function testgeneratejobdescription()
{
$jobdescriptionparams = new jobdescriptionparameters(
"backend developer",
"innovatetech",
"3 years",
"bachelor's degree in computer science",
"full-time",
["develop apis", "optimize database queries"],
["proficiency in php and laravel", "experience with restful apis"],
"usa",
true,
true,
"professional",
"category b driving license",
"english"
);
$statusurl = $this->sharpapi->generatejobdescription($jobdescriptionparams);
$resultjob = $this->sharpapi->fetchresults($statusurl);
$this->assertequals('completed', $resultjob->getstatus());
$this->assertnotempty($resultjob->getresultobject());
}
// add more tests for other methods...
}
使用 phpunit 执行测试。
./vendor/bin/phpunit
要同时处理多个 api 请求,请考虑使用 laravel 队列实现异步处理。
在 .env 文件中配置队列驱动程序。
queue_connection=database
运行必要的迁移。
php artisan queue:table php artisan migrate
php artisan make:job processsharpapirequest
<?php
namespace app\jobs;
use illuminate\bus\queueable;
use illuminate\contracts\queue\shouldqueue;
use illuminate\foundation\bus\dispatchable;
use illuminate\queue\interactswithqueue;
use illuminate\queue\serializesmodels;
use app\services\sharpapiclient;
use sharpapi\dto\jobdescriptionparameters;
class processsharpapirequest implements shouldqueue
{
use dispatchable, interactswithqueue, queueable, serializesmodels;
protected $params;
public function __construct(jobdescriptionparameters $params)
{
$this->params = $params;
}
public function handle(sharpapiclient $sharpapi)
{
$statusurl = $sharpapi->generatejobdescription($this->params);
$resultjob = $sharpapi->fetchresults($statusurl);
// handle the result...
}
}
use app\jobs\processsharpapirequest;
public function generatejobdescriptionasync()
{
$jobdescriptionparams = new jobdescriptionparameters(
// ... parameters
);
processsharpapirequest::dispatch($jobdescriptionparams);
return response()->json(['message' => 'job dispatched successfully.']);
}
php artisan queue:work
为了优化性能并减少冗余 api 调用,请实施缓存。
use illuminate\support\facades\cache;
public function generatejobdescription()
{
$cachekey = 'job_description_' . md5(json_encode($jobdescriptionparams));
$result = cache::remember($cachekey, 3600, function () use ($jobdescriptionparams) {
$statusurl = $this->sharpapi->generatejobdescription($jobdescriptionparams);
$resultjob = $this->sharpapi->fetchresults($statusurl);
return $resultjob->getresultjson();
});
return response()->json(json_decode($result, true));
}
底层数据发生变化时,确保相关缓存失效。
Cache::forget('job_description_' . md5(json_encode($jobDescriptionParams)));
将 sharpapi 集成到您的 laravel 应用程序中可以解锁大量人工智能驱动的功能,增强您的应用程序的功能并提供无缝的工作流程自动化。本指南引导您完成从设置身份验证到进行 api 调用和处理响应的基本步骤。通过提供的示例和最佳实践,您已经准备好在 laravel 项目中利用 sharpapi 的强大功能。
如果您遇到任何问题或对集成过程有疑问,请随时在 github 存储库上提出问题,或通过 contact@sharpapi.com 联系我们的支持团队。
该项目已获得 mit 许可。
以上就是SharpAPI Laravel 集成指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号