简体   繁体   English

Laravel 中第三方 API 连接的最佳位置

[英]Best location in Laravel for third-party API connection

I'm writing a Laravel application using one or more third-party APIs when it suddenly dawned on me.我正在使用一个或多个第三方 API 编写 Laravel 应用程序时突然想到它。 Where is the best place within the Laravel application structure to set up the API connection to consume it from my Controller? Laravel 应用程序结构中设置 API 连接以从我的控制器使用它的最佳位置在哪里? Would you use a Service or put the logic somewhere else?您会使用服务还是将逻辑放在其他地方?

$this->api = new RestApi();
    ->setUrl(getenv('API_REST_URL'))
    ->setUsername(getenv('API_USERNAME'))
    ->setPassword(getenv('API_PASSWORD'))
    ->connect();

Using services would be the better approach in Laravel, once your third party is not a direct route or content in your API, per se, it should not be in your Controller.在 Laravel 中使用服务将是更好的方法,一旦您的第三方不是 API 中的直接路由或内容,它本身就不应该在您的控制器中。 You may want to use a Service with Guzzle.您可能希望通过 Guzzle 使用服务。

I think the best answer is that it depends on the size of your project and what you are doing.我认为最好的答案是这取决于你的项目规模和你在做什么。

This post lists 3 of the most common ways.这篇文章列出了 3 种最常见的方式。 I would go with Method 3 myself (Register the API with the service container), even for simple things.我会自己使用方法 3(使用服务容器注册 API),即使是简单的事情。 It abstracts it away nicely so should work best in all situations.它很好地将其抽象出来,因此应该在所有情况下都能发挥最佳效果。

https://desertebs.com/laravel/how-to-consume-external-third-party-api-in-laravel-5 https://deserebs.com/laravel/how-to-consume-external-third-party-api-in-laravel-5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM