控制器Laravel的Call API最佳做法

时间:2019-05-10 05:24:22

标签: laravel api laravel-5 call

使用laravel中的助手从控制器调用API的最佳实践是什么? 我需要从其他控制器调用serval API,所以I need a helper for this最好。

我使用了curl,但是它总是给我一个错误的答复。

1 个答案:

答案 0 :(得分:4)

您可以使用Guzzle pacakge docs:https://github.com/guzzle/guzzle

安装

composer require guzzlehttp/guzzle

获取

    $client = new \GuzzleHttp\Client();
    $request = $client->get('example.com');
    $response = $request->getBody();
    return $response;

POST

    $client = new \GuzzleHttp\Client();
    $body['name'] = "Testing";
    $url = "http://my-domain.com/api/v1/post";
    $response = $client->createRequest("POST", $url, ['body'=>$body]);
    $response = $client->send($response);
    return $response;

一些有用的方法

    $response->getStatusCode(); # 200
    $response->getHeaderLine('content-type'); # 'application/json; charset=utf8'
    $response->getBody(); # '{"id": 1420053, "name": "guzzle", ...}'
  • 我们还可以发送异步请求
    $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
    $promise = $client->sendAsync($request)->then(function ($response) {
        echo 'I completed! ' . $response->getBody();
    });
    $promise->wait();
  • 我们还可以添加标题
    $header = array('Authorization'=>'token');
    $client = new \GuzzleHttp\Client();
    $request = $client->get('example.com',array('headers' => $header));
    $response = $request->getBody();

此方法的助手

我们可以为这些方法创建一个公共帮助器。 *首先在应用程序文件夹中创建文件夹

    app\Helper
  • 然后在Helper文件夹中创建一个文件
    app\Helper\helper.php
  • 将此代码添加到helper.php中
<?php 

namespace App\Helper;
class Helper
{

    public static function GetApi($url)
    {
        $client = new \GuzzleHttp\Client();
        $request = $client->get($url);
        $response = $request->getBody();
        return $response;
    }


    public static function PostApi($url,$body) {
        $client = new \GuzzleHttp\Client();
        $response = $client->createRequest("POST", $url, ['body'=>$body]);
        $response = $client->send($response);
        return $response;
    }
}

  • 现在可以使用控制器
    use App\Helper\Helper;
    Helper::GetApi('ultimateakash.com');

我们也可以在没有帮助者的情况下做到这一点

  • 在主控制器中,我们可以创建这些功能
<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function GetApi($url)
    {
        $client = new \GuzzleHttp\Client();
        $request = $client->get($url);
        $response = $request->getBody();
        return $response;
    }


    public function PostApi($url,$body) {
        $client = new \GuzzleHttp\Client();
        $response = $client->createRequest("POST", $url, ['body'=>$body]);
        $response = $client->send($response);
        return $response;
    }
}
  • 现在在控制器中我们可以调用
    $this->GetApi('ultimateakash.com');