SharpAPI Laravel 統合ガイド

Oct 07, 2024 am 06:07 AM

SharpAPI Laravel Integration Guide

SharpAPI Laravel 統合ガイド へようこそ!このリポジトリは、SharpAPI を次の Laravel AI アプリケーションに統合する方法に関する包括的なステップバイステップのチュートリアルを提供します。 ** AI を活用した機能** でアプリを強化したい場合でも、ワークフローを自動化する場合でも、このガイドでは、認証から API 呼び出しの実行と応答の処理までのプロセス全体を説明します。

記事は https://github.com/sharpapi/laravel-ai-integration-guide で Github リポジトリとしても公開されています。


目次

  1. 前提条件
  2. Laravel プロジェクトのセットアップ
  3. SharpAPI PHP クライアントのインストール
  4. 構成
    • 環境変数
  5. SharpAPI による認証
  6. API呼び出しの実行
    • 例: 職務記述書の生成
  7. 応答の処理
  8. エラー処理
  9. 統合のテスト
  10. 高度な使用法
    • 非同期リクエスト
    • 応答のキャッシュ
  11. 結論
  12. サポート
  13. ライセンス

前提条件

始める前に、次の要件を満たしていることを確認してください:

  • PHP: >= 8.1
  • Composer: PHP の依存関係マネージャー
  • Laravel: バージョン 9 以降
  • SharpAPI アカウント: SharpAPI.com から API キーを取得します。
  • Laravel の基礎知識: Laravel フレームワークと MVC アーキテクチャに関する知識

Laravelプロジェクトのセットアップ

Laravel プロジェクトがすでにある場合は、このステップをスキップできます。それ以外の場合は、次の手順に従って新しい Laravel プロジェクトを作成します。

  1. Composer 経由で Laravel をインストールします

   composer create-project --prefer-dist laravel/laravel laravel-ai-integration-guide


ログイン後にコピー
  1. プロジェクト ディレクトリに移動します

   cd laravel-ai-integration-guide


ログイン後にコピー
  1. アプリケーションを提供する

   php artisan serve


ログイン後にコピー

アプリケーションは http://localhost:8000 でアクセスできます。


SharpAPI PHP クライアントのインストール

SharpAPI と対話するには、SharpAPI PHP クライアント ライブラリをインストールする必要があります。

Composer 経由で SharpAPI パッケージが必要です


composer require sharpapi/sharpapi-laravel-client
php artisan vendor:publish --tag=sharpapi-laravel-client


ログイン後にコピー

構成

環境変数

API キーなどの機密情報を環境変数に保存することがベスト プラクティスです。 Laravel は、環境固有の構成に .env ファイルを使用します。

  1. .env ファイルを開きます

Laravel プロジェクトのルート ディレクトリにあります。

  1. SharpAPI API キーを追加します

   SHARP_API_KEY=your_actual_sharpapi_api_key_here


ログイン後にコピー

: your_actual_sharpapi_api_key_here を実際の SharpAPI API キーに置き換えます。

  1. コードでの環境変数へのアクセス

Laravel は、環境変数にアクセスするための env ヘルパー関数を提供します。


   $apiKey = env('SHARP_API_KEY');


ログイン後にコピー

SharpAPIによる認証

SharpAPI のエンドポイントと安全にやり取りするには認証が必要です。

  1. 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;
       }
   }


ログイン後にコピー
  1. サービスプロバイダーでのサービスのバインド (オプション)

これにより、必要な場所にサービスを挿入できます。


   <?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()
       {
           //
       }
   }


ログイン後にコピー
  1. コントローラーでのサービスの使用

   <?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);
       }
   }


ログイン後にコピー
  1. ルートの定義

ルートをroutes/web.phpまたはroutes/api.phpに追加します:


   use App\Http\Controllers\SharpApiController;

   Route::get('/sharpapi/ping', [SharpApiController::class, 'ping']);


ログイン後にコピー

API呼び出しの実行

認証されると、さまざまな SharpAPI エンドポイントへの API 呼び出しを開始できるようになります。以下は、さまざまなエンドポイントと対話する方法の例です。

例: 職務記述書の生成

  1. ジョブ記述パラメータ DTO の作成

   <?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());
       }
   }


ログイン後にコピー
  1. ルートを定義します

   Route::get('/sharpapi/generate-job-description', [SharpApiController::class, 'generateJobDescription']);


ログイン後にコピー
  1. エンドポイントへのアクセス

生成されたジョブの説明を確認するには、http://localhost:8000/sharpapi/generate-job-description にアクセスしてください。


応答の処理

SharpAPI 応答は通常、ジョブ オブジェクトにカプセル化されます。これらの応答を効果的に処理するには:

  1. 応答構造を理解する

   {
       "id": "uuid",
       "type": "JobType",
       "status": "Completed",
       "result": {
           // Result data
       }
   }


ログイン後にコピー
  1. 結果へのアクセス

提供されたメソッドを使用して結果データにアクセスします。


   $resultJob = $this->sharpApi->fetchResults($statusUrl);
   $resultData = $resultJob->getResultObject(); // As a PHP object
   // or
   $resultJson = $resultJob->getResultJson(); // As a JSON string


ログイン後にコピー
  1. Example Usage in Controller

   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);
       }
   }


ログイン後にコピー

Error Handling

Proper error handling ensures that your application can gracefully handle issues that arise during API interactions.

  1. Catching Exceptions

Wrap your API calls in try-catch blocks to handle exceptions.


   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);
       }
   }


ログイン後にコピー
  1. Handling API Errors

Check the status of the job and handle different statuses accordingly.


   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);
   }


ログイン後にコピー

Testing the Integration

Testing is crucial to ensure that your integration with SharpAPI works as expected.

  1. Writing Unit Tests

Use Laravel's built-in testing tools to write unit tests for your SharpAPI integration.


   <?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...
   }


ログイン後にコピー
  1. Running Tests

Execute your tests using PHPUnit.


   ./vendor/bin/phpunit


ログイン後にコピー

Advanced Usage

Asynchronous Requests

For handling multiple API requests concurrently, consider implementing asynchronous processing using Laravel Queues.

  1. Setting Up Queues

Configure your queue driver in the .env file.


   QUEUE_CONNECTION=database


ログイン後にコピー

Run the necessary migrations.


   php artisan queue:table
   php artisan migrate


ログイン後にコピー
  1. Creating a Job

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


ログイン後にコピー
  1. Dispatching the Job

   use App\Jobs\ProcessSharpApiRequest;

   public function generateJobDescriptionAsync()
   {
       $jobDescriptionParams = new JobDescriptionParameters(
           // ... parameters
       );

       ProcessSharpApiRequest::dispatch($jobDescriptionParams);
       return response()->json(['message' => 'Job dispatched successfully.']);
   }


ログイン後にコピー
  1. Running the Queue Worker

   php artisan queue:work


ログイン後にコピー

Caching Responses

To optimize performance and reduce redundant API calls, implement caching.

  1. Using Laravel's Cache Facade

   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));
   }


ログイン後にコピー
  1. Invalidating Cache

When the underlying data changes, ensure to invalidate the relevant cache.


   Cache::forget('job_description_' . md5(json_encode($jobDescriptionParams)));


ログイン後にコピー

Conclusion

Integrating SharpAPI into your Laravel application unlocks a myriad of AI-powered functionalities, enhancing your application's capabilities and providing seamless workflow automation. This guide has walked you through the essential steps, from setting up authentication to making API calls and handling responses. With the examples and best practices provided, you're well-equipped to leverage SharpAPI's powerful features in your Laravel projects.


Support

If you encounter any issues or have questions regarding the integration process, feel free to open an issue on the GitHub repository or contact our support team at contact@sharpapi.com.


License

This project is licensed under the MIT License.


以上がSharpAPI Laravel 統合ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

中国語版、とても使いやすい

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

SublimeText3 Mac版

SublimeText3 Mac版

神レベルのコード編集ソフト(SublimeText3)

JSON Web Tokens(JWT)とPHP APIでのユースケースを説明してください。 JSON Web Tokens(JWT)とPHP APIでのユースケースを説明してください。 Apr 05, 2025 am 12:04 AM

JWTは、JSONに基づくオープン標準であり、主にアイデンティティ認証と情報交換のために、当事者間で情報を安全に送信するために使用されます。 1。JWTは、ヘッダー、ペイロード、署名の3つの部分で構成されています。 2。JWTの実用的な原則には、JWTの生成、JWTの検証、ペイロードの解析という3つのステップが含まれます。 3. PHPでの認証にJWTを使用する場合、JWTを生成および検証でき、ユーザーの役割と許可情報を高度な使用に含めることができます。 4.一般的なエラーには、署名検証障害、トークンの有効期限、およびペイロードが大きくなります。デバッグスキルには、デバッグツールの使用とロギングが含まれます。 5.パフォーマンスの最適化とベストプラクティスには、適切な署名アルゴリズムの使用、有効期間を合理的に設定することが含まれます。

PHP 8.1の列挙(列挙)とは何ですか? PHP 8.1の列挙(列挙)とは何ですか? Apr 03, 2025 am 12:05 AM

php8.1の列挙関数は、指定された定数を定義することにより、コードの明確さとタイプの安全性を高めます。 1)列挙は、整数、文字列、またはオブジェクトであり、コードの読みやすさとタイプの安全性を向上させることができます。 2)列挙はクラスに基づいており、トラバーサルや反射などのオブジェクト指向の機能をサポートします。 3)列挙を比較と割り当てに使用して、タイプの安全性を確保できます。 4)列挙は、複雑なロジックを実装するためのメソッドの追加をサポートします。 5)厳密なタイプのチェックとエラー処理は、一般的なエラーを回避できます。 6)列挙は魔法の価値を低下させ、保守性を向上させますが、パフォーマンスの最適化に注意してください。

セッションのハイジャックはどのように機能し、どのようにPHPでそれを軽減できますか? セッションのハイジャックはどのように機能し、どのようにPHPでそれを軽減できますか? Apr 06, 2025 am 12:02 AM

セッションハイジャックは、次の手順で達成できます。1。セッションIDを取得します。2。セッションIDを使用します。3。セッションをアクティブに保ちます。 PHPでのセッションハイジャックを防ぐための方法には次のものが含まれます。1。セッション_regenerate_id()関数を使用して、セッションIDを再生します。2。データベースを介してストアセッションデータを3。

確固たる原則と、それらがPHP開発にどのように適用されるかを説明してください。 確固たる原則と、それらがPHP開発にどのように適用されるかを説明してください。 Apr 03, 2025 am 12:04 AM

PHP開発における固体原理の適用には、次のものが含まれます。1。単一責任原則(SRP):各クラスは1つの機能のみを担当します。 2。オープンおよびクローズ原理(OCP):変更は、変更ではなく拡張によって達成されます。 3。Lischの代替原則(LSP):サブクラスは、プログラムの精度に影響を与えることなく、基本クラスを置き換えることができます。 4。インターフェイス分離原理(ISP):依存関係や未使用の方法を避けるために、細粒インターフェイスを使用します。 5。依存関係の反転原理(DIP):高レベルのモジュールと低レベルのモジュールは抽象化に依存し、依存関係噴射を通じて実装されます。

PHPでの後期静的結合を説明します(静的::)。 PHPでの後期静的結合を説明します(静的::)。 Apr 03, 2025 am 12:04 AM

静的結合(静的::) PHPで後期静的結合(LSB)を実装し、クラスを定義するのではなく、静的コンテキストで呼び出しクラスを参照できるようにします。 1)解析プロセスは実行時に実行されます。2)継承関係のコールクラスを検索します。3)パフォーマンスオーバーヘッドをもたらす可能性があります。

REST APIデザインの原則とは何ですか? REST APIデザインの原則とは何ですか? Apr 04, 2025 am 12:01 AM

Restapiの設計原則には、リソース定義、URI設計、HTTPメソッドの使用、ステータスコードの使用、バージョンコントロール、およびHATEOASが含まれます。 1。リソースは名詞で表され、階層で維持される必要があります。 2。HTTPメソッドは、GETを使用してリソースを取得するなど、セマンティクスに準拠する必要があります。 3.ステータスコードは、404など、リソースが存在しないことを意味します。 4。バージョン制御は、URIまたはヘッダーを介して実装できます。 5。それに応じてリンクを介してhateoasブーツクライアント操作をブーツします。

PHPで例外を効果的に処理する方法(試して、キャッチ、最後に、スロー)? PHPで例外を効果的に処理する方法(試して、キャッチ、最後に、スロー)? Apr 05, 2025 am 12:03 AM

PHPでは、Try、Catch、最後にキーワードをスローすることにより、例外処理が達成されます。 1)TRYブロックは、例外をスローする可能性のあるコードを囲みます。 2)キャッチブロックは例外を処理します。 3)最後にブロックは、コードが常に実行されることを保証します。 4)スローは、例外を手動でスローするために使用されます。これらのメカニズムは、コードの堅牢性と保守性を向上させるのに役立ちます。

PHPの匿名クラスとは何ですか?また、いつ使用できますか? PHPの匿名クラスとは何ですか?また、いつ使用できますか? Apr 04, 2025 am 12:02 AM

PHPの匿名クラスの主な機能は、1回限りのオブジェクトを作成することです。 1.匿名クラスでは、名前のないクラスをコードで直接定義することができます。これは、一時的な要件に適しています。 2。クラスを継承したり、インターフェイスを実装して柔軟性を高めることができます。 3.使用時にパフォーマンスとコードの読みやすさに注意し、同じ匿名のクラスを繰り返し定義しないようにします。

See all articles