SharpAPI Laravel 集成指南

Mary-Kate Olsen
发布: 2024-10-07 06:07:29
原创
722 人浏览过

SharpAPI Laravel Integration Guide

Selamat datang ke Panduan Penyepaduan SharpAPI Laravel! Repositori ini menyediakan tutorial langkah demi langkah yang komprehensif tentang cara mengintegrasikan SharpAPI ke dalam aplikasi AI Laravel anda yang seterusnya. Sama ada anda ingin meningkatkan apl anda dengan** ciri dikuasakan AI** atau mengautomatikkan aliran kerja, panduan ini akan membimbing anda melalui keseluruhan proses, daripada pengesahan kepada membuat panggilan API dan mengendalikan respons.

Artikel diterbitkan juga sebagai repositori Github di https://github.com/sharpapi/laravel-ai-integration-guide.


Jadual Kandungan

  1. Prasyarat
  2. Menyediakan Projek Laravel
  3. Memasang Klien PHP SharpAPI
  4. Konfigurasi
    • Pembolehubah Persekitaran
  5. Pengesahan dengan SharpAPI
  6. Membuat Panggilan API
    • Contoh: Menjana Penerangan Kerja
  7. Mengendalikan Respons
  8. Pengendalian Ralat
  9. Menguji Integrasi
  10. Penggunaan Lanjutan
    • Permintaan Tak Segerak
    • Caching Respons
  11. Kesimpulan
  12. Sokongan
  13. Lesen

Prasyarat

Sebelum anda bermula, pastikan anda telah memenuhi keperluan berikut:

  • PHP: >= 8.1
  • Komposer: Pengurus kebergantungan untuk PHP
  • Laravel: Versi 9 atau lebih tinggi
  • Akaun SharpAPI: Dapatkan kunci API daripada SharpAPI.com
  • Pengetahuan Asas Laravel: Kebiasaan dengan rangka kerja Laravel dan seni bina MVC

Menyediakan Projek Laravel

Jika anda sudah mempunyai projek Laravel, anda boleh melangkau langkah ini. Jika tidak, ikut arahan ini untuk mencipta projek Laravel baharu.

  1. Pasang Laravel melalui Komposer

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


登录后复制
  1. Navigasi ke Direktori Projek

   cd laravel-ai-integration-guide


登录后复制
  1. Layankan Permohonan

   php artisan serve


登录后复制

Aplikasi ini boleh diakses di http://localhost:8000.


Memasang Klien PHP SharpAPI

Untuk berinteraksi dengan SharpAPI, anda perlu memasang pustaka klien PHP SharpAPI.

Memerlukan Pakej SharpAPI melalui Komposer


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


登录后复制

Konfigurasi

Pembolehubah Persekitaran

Menyimpan maklumat sensitif seperti kunci API dalam pembolehubah persekitaran ialah amalan terbaik. Laravel menggunakan fail .env untuk konfigurasi khusus persekitaran.

  1. Buka Fail .env

Terletak dalam direktori akar projek Laravel anda.

  1. Tambahkan Kunci API SharpAPI Anda

   SHARP_API_KEY=your_actual_sharpapi_api_key_here


登录后复制

Nota: Gantikan_actual_sharpapi_api_key_di sini dengan kunci API SharpAPI anda yang sebenar.

  1. Mengakses Pembolehubah Persekitaran dalam Kod

Laravel menyediakan fungsi env helper untuk mengakses pembolehubah persekitaran.


   $apiKey = env('SHARP_API_KEY');


登录后复制

Pengesahan dengan SharpAPI

Pengesahan diperlukan untuk berinteraksi dengan titik akhir SharpAPI dengan selamat.

  1. Mulakan Klien SharpAPI

Buat perkhidmatan atau gunakannya terus dalam pengawal anda.


   <?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. Mengikat Perkhidmatan dalam Pembekal Perkhidmatan (Pilihan)

Ini membolehkan anda menyuntik perkhidmatan di mana sahaja diperlukan.


   <?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. Menggunakan Perkhidmatan dalam Pengawal

   <?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. Menentukan Laluan

Tambah laluan ke route/web.php atau route/api.php:


   use App\Http\Controllers\SharpApiController;

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


登录后复制

Membuat Panggilan API

Setelah disahkan, anda boleh mula membuat panggilan API ke pelbagai titik akhir SharpAPI. Di bawah ialah contoh cara berinteraksi dengan titik akhir yang berbeza.

Contoh: Menjana Penerangan Kerja

  1. Buat Parameter Perihalan Kerja 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. Tentukan Laluan

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


登录后复制
  1. Mengakses Titik Akhir

Lawati http://localhost:8000/sharpapi/generate-job-description untuk melihat huraian kerja yang dijana.


Mengendalikan Respons

Respons SharpAPI biasanya terkandung dalam objek kerja. Untuk mengendalikan respons ini dengan berkesan:

  1. Memahami Struktur Respons

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


登录后复制
  1. Mengakses Keputusan

Gunakan kaedah yang disediakan untuk mengakses data hasil.


   $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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板