prateekkathal/laravel-simplecurl 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

prateekkathal/laravel-simplecurl

Composer 安装命令:

composer create-project prateekkathal/laravel-simplecurl

包简介

A Laravel package for handling simple CURL requests

README 文档

README

A Laravel package for handling simple CURL requests... the Laravel way...

For installation,

  • In terminal, paste this
composer require prateekkathal/laravel-simplecurl 0.*
  • Open app.php and add this in the 'providers' array
PrateekKathal\SimpleCurl\SimpleCurlServiceProvider::class,
  • Then add this to the 'aliases' array
'SimpleCurl' => PrateekKathal\SimpleCurl\SimpleCurlFacade::class,

Request Functions

Function Name Return Type Example
get() SimpleCurl SimpleCurl::get($url = '', $data = [], $headers = [])
post() SimpleCurl SimpleCurl::post($url = '', $data = [], $headers = [], $file = false)
put() SimpleCurl SimpleCurl::put($url = '', $data = [], $headers = [])
delete() SimpleCurl SimpleCurl::delete($url = '', $data = [], $headers = [])

Response Functions

Function Name Return Type Example
getResponse() array ['http_code' => 200, 'result' => ...]
getResponseCode() array 200
getRequestUrl() string 'http://mysite.com/api/v1/....'
getRequestSize() int 300
getTotalTime() int 0.2
getResponseContentType() string 'application/json'
getRedirectCount() int 0
getEffectiveUrl() string 'http://mysite.com/api/v1/....'
getCurlError() string 'URL is not properly formatted'
getResponseAsArray() array ['id' => 1, 'name' => Prateek Kathal ...]
getResponseAsJson() json {"id": 1, "name": "Prateek Kathal" ...}
getResponseAsCollection() Collection Collection => { [ 0 => {"id": 1, "name": "Prateek Kathal" }... ] }
getPaginatedResponse() LengthAwarePaginator LengthAwarePaginator => { 'total' => 10, per_page => 10, data => [ { "id": 1, "name": "Prateek Kathal" }... } ]
getResponseAsModel() Model User => { "attributes" : { "id": 1, "name": "Prateek Kathal" } }

Making simple GET/POST/PUT/DELETE requests,

Without Config Variables

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

}

You may also use this function just for making things more Laravel-like...

**Add this trait to your Model (say Photo)

use PrateekKathal\SimpleCurl\SimpleCurlTrait;

** Then add these 2 things in your model**

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

Please note that getResponseAsModel() is experimental and may not run for many cases if the responses are altered a lot before they are sent. For eg - When you convert an attribute created_at into a separate format using $casts variable.

Also, you can make a config file (say config/relations.php) and save all your relations in it and call separately.

With Config Variables

<?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/',
      'buildQuery' => false,
      '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']);

    // you can also change the default UserAgent
    // $simpleCurl = SimpleCurl::setUserAgent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");

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

    and so on...
  }

  and so on.....

}

You are most welcome to create pull requests and post issues! 😄 😎 👍

prateekkathal/laravel-simplecurl 适用场景与选型建议

prateekkathal/laravel-simplecurl 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 6.73k 次下载、GitHub Stars 达 8, 最近一次更新时间为 2016 年 09 月 10 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「php」 「curl」 「laravel」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 prateekkathal/laravel-simplecurl 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 prateekkathal/laravel-simplecurl 我们能提供哪些服务?
定制开发 / 二次开发

基于 prateekkathal/laravel-simplecurl 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 6.73k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 8
  • 点击次数: 3
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 8
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-09-10