【问题标题】:Laravel – Calling API connectionsLaravel – 调用 API 连接
【发布时间】:2016-07-05 01:57:22
【问题描述】:

重复调用 – 假设您需要您的应用程序与 API 通信,并且您正在使用 guzzle 或包装器或其他任何东西。我发现自己必须在每个控制器函数中调用连接,例如:

class ExampleController extends Controller
{

    public function one()
    {

      $client = new Client();
      $response = $client->get('http://', 
      [ 'query'  => [ 'secret' => env('SECRET')]]);

      $json = json_decode($response->getBody());
      $data =  $json->object;

      // do stuff
    }

    public function two()
    {
      $client = new Client();
      $response = $client->get('http://', 
      [ 'query'  => [ 'secret' =>  env('SECRET')]]);

      $json = json_decode($response->getBody());
      $data =  $json->object;

      // do stuff
    }
}

我该如何更好地处理这个问题?我是否使用服务提供商?如果是这样,我将如何最好地实现这些调用?我是否应该创建另一个控制器并在每个函数中调用我的所有 API 连接,然后包含该控制器并根据需要调用每个函数?我应该把它放在__construct?

【问题讨论】:

    标签: php api laravel model-view-controller


    【解决方案1】:

    让我们试试依赖倒置原则

    好吧,这听起来可能有点难,我的代码可能有一些拼写错误或小错误,但试试这个

    你需要创建接口

    namespace app\puttherightnamespace; // this deppends on you
    
    interface ExempleRepositoryInterface 
    {
        public function getquery(); // if you passinga  variable -> public function getquery('variable1');
    
    }
    

    现在您必须创建存储库

    class ExempleRepository implements ExempleRepositoryInterface {
    
     public function getquery() {
    
      $client = new Client();
      $response = $client->get('http://', 
      [ 'query'  => [ 'secret' => env('SECRET')]]);
    
      $json = json_decode($response->getBody());
    
       return $json->object;
    }
    

    现在最后一步是在服务提供者注册方法中将接口绑定到 repo

    public function register()
     {
       $this->app->bind('namespacehere\ExempleRepositoryInterface', 'namespacehere\ExempleRepository');
      }
    

    现在每次你需要控制器中的结果时,你所要做的就是注入

    class ExempleController extends Controller {
            private $exemple;
            public function __construct(ExempleRepositoryInterface $home) {
                $this->exemple = $exemple;
            }
            public function test() {
                $data = $this->exemple->getquery(); / you can pass a variable here if you want like this $this->exemple->getquery('variable');
    
                // do stuff
            }
    

    这不是最简单的方法,但这是我认为最好的方法

    【讨论】:

    • 非常感谢!这对我有很大帮助。几个问题,我将接口和 repo 放在 laravel 目录的哪里? (在 /controllers 中?)与服务提供商一起,我会将其添加到我的 AppServiceProvider 文件中吗?
    • 否,在 app 文件夹内(或在其外)创建另一个文件夹并将 repos 放在那里,是的,或者您可以将其添加到您的应用服务提供商或创建新的服务提供商(顺便说一句,您将拥有编辑 composer.json 以自动加载新文件夹以使工作正常)
    猜你喜欢
    • 1970-01-01
    • 2017-09-23
    • 2018-01-17
    • 2015-12-28
    • 1970-01-01
    • 2016-06-06
    • 2016-03-22
    • 2021-09-05
    • 2013-04-03
    相关资源
    最近更新 更多