squareboat/laravel-simplecurl

一个用于处理简单 CURL 请求的 Laravel 扩展包

v0.2.4 2017-04-18 06:59 UTC

This package is auto-updated.

Last update: 2024-09-04 16:18:34 UTC


README

一个用于处理简单 CURL 请求的 Laravel 扩展包... 采用 Laravel 风格...

安装方法:

  • 在终端中粘贴以下内容
composer require squareboat/laravel-simplecurl 0.*
  • 打开 app.php 并在 'providers' 数组中添加以下内容
SquareBoat\SimpleCurl\SimpleCurlServiceProvider::class,
  • 然后添加到 'aliases' 数组中
'SimpleCurl' => SquareBoat\SimpleCurl\SimpleCurlFacade::class,

请求函数

响应函数

进行简单的 GET/POST/PUT/DELETE 请求,

不使用配置变量

<?php

use SimpleCurl;

class UsersApiRepo
{

  function allUsers()
  {
    // Gives Response As Array
    $usersArray = SimpleCurl::get('http://mysite.com/api/v1/user/all')->getResponseAsArray();

    // Or (Gives Response As Json)
    $usersJson = SimpleCurl::get('http://mysite.com/api/v1/user/all')->getResponseAsJson();

    // Or (Gives Response As Collection)
    $usersCollection = SimpleCurl::get('http://mysite.com/api/v1/user/all')->getResponseAsCollection();

    // Or (Gives Response As LengthAwarePaginator, if the response is paginated)
    $usersPaginated = SimpleCurl::get('http://mysite.com/api/v1/user/all')->getPaginatedResponse();
  }

  function storeUser()
  {
    $url = 'http://mysite.com/api/v1/user/store';
    $inputs = [
      'name' => 'Prateek Kathal',
      'status' => 'Feeling positive!',
      'photo' => new \CURLFile($photoUrl, $mimeType, $photoName)
    ];
    $headers = ['Authorization: Bearer tokenForAuthorization'];
    $usersJson = SimpleCurl::post($url, $inputs, $headers, true)->getResponseAsJson();
  }

  function updateUser($id)
  {
    // Please note that CURL does not support posting Images/Files via PUT requests.
    $url = 'http://mysite.com/api/v1/user/' .$id. '/update';
    $headers = ['Authorization: Bearer tokenForAuthorization'];
    $inputs = [
      'status' => 'Feeling amazing!'
    ];
    $usersJson = SimpleCurl::put($url, $inputs, $headers)->getResponseAsJson();
  }

  function deleteUser($id)
  {
    // Please note that CURL does not support posting Images/Files via PUT requests.
    $url = 'http://mysite.com/api/v1/user/' .$id. '/delete';
    $headers = ['Authorization: Bearer tokenForAuthorization'];
    $usersJson = SimpleCurl::put($url, [], $headers)->getResponseAsJson();
  }

}

您还可以使用此函数来使代码更具有 Laravel 风格...

**将此特质添加到您的模型(例如 Photo)中

use SquareBoat\SimpleCurl\SimpleCurlTrait;

**然后在您的模型中添加以下两项

<?php

class Photo extends Model
{
  use SimpleCurlTrait;

  protected $apiAttributes = ['id', 'user_id', 'name', 'mime_type'];
}
function getUser($id)
{
  /*
   * Please ensure only a single Model is present in the response for this. Multiple rows will not be
   * automatically get converted into Collections And Models atm.
   *
   * Keys set as fillable in that particular model are used here. Any fillable key, not present in the
   * response will be set as null and an instance of the Model will be returned.
   */
  $userModel = SimpleCurl::get('http://mysite.com/api/v1/user/' .id. '/get/')->getResponseAsModel('App\User')

  /*
   * There is also a second parameter which you can use to add something from the response as a relation
   * to it.
   *
   * You will have to save a copy of the model somewhere so that SimpleCurl can get apiAttributes/fillable fields from
   * that class and use for relational Models as well.
   */
  $relations = [
    [
      'photo' => 'App\Photo'
    ],
    [
      'city'=> 'App\City',                  //This will work as city.state and give state as a relation to city
      'state' => 'App\State'
    ]
  ];
  $userModelWithPhotoAsRelation = SimpleCurl::get('http://mysite.com/api/v1/user/' .id. '/get/')->getResponseAsModel('App\User', $relations);
}

请注意,getResponseAsModel() 是实验性的,如果响应在发送之前被大量更改,可能不会在许多情况下运行。例如,当您使用 $casts 变量将属性 created_at 转换为单独的格式时。

此外,您还可以创建一个配置文件(例如 config/relations.php),在其中保存所有关系,并单独调用。

使用配置变量

<?php

use SimpleCurl;

class UsersApiRepo
{

  /*
   * A Config Variable which you can use to handle multiple CURL requests...
   */
  protected $simpleCurlConfig;

  function __construct() {
    $this->simpleCurlConfig = [
      'connectTimeout' => 30,
      'dataTimeout' => 60,
      'baseUrl' => 'http://mysite.com/',
      'defaultHeaders' => [
        'Authorization: Bearer {bearer_token}',
        'Content-Type: application/json'
      ],
    ];
  }

  function allUsers()
  {
    // Set Defaults for making a CURL Request
    $simpleCurl = SimpleCurl::setConfig($this->simpleCurlConfig);

    // or if you just want to set base url
    // $simpleCurl = SimpleCurl::setBaseUrl($this->simpleCurlConfig['baseUrl']);

    // Gives Response As Array
    $usersArray = $simpleCurl->get('api/v1/users/all')->getResponseAsArray();

    and so on...
  }

  and so on.....

}

欢迎您创建 pull request 并提交 issues! 😄 😎 👍