简体   繁体   English

将 Laravel 服务容器用于第三方 API

[英]Using Laravel Service Container for third-party APIs

I'm trying to make proper use of Laravel's Service Container to instantiate a connection to a third-party API and use it across my Controllers.我正在尝试正确使用 Laravel 的服务容器来实例化与第三方 API 的连接并在我的控制器中使用它。 Below I added my API connection into the register method of Laravel's AppServiceProvider.下面我将我的 API 连接添加到 Laravel 的 AppServiceProvider 的注册方法中。 In my Controller constructor, I provide a handle to that connection that can be used freely inside the Controller wherever a connection is needed.在我的 Controller 构造函数中,我提供了该连接的句柄,该句柄可以在需要连接的任何地方在 Controller 内自由使用。 Does this example demonstrate the best use of a Service Container?此示例是否展示了服务容器的最佳用途? Should I replace my reference to 'bind' with 'singleton' instead?我应该用“单例”代替我对“绑定”的引用吗?

use App\Http\Clients\RestClient;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(RestClient::class, function($app)
        {
            $this->api = new RestClient();
            $this->api->setUrl(getenv('API_REST_URL'))
                    ->setUsername(getenv('API_USERNAME'))
                    ->setPassword(getenv('API_PASSWORD'))
                    ->connect();

            return $this->api;
        });
    }
} 

class LoginController extends Controller 
{
    public function __construct(RestClient $api) 
    {
        $this->api = $api;
    }

    public function postLogin() 
    {
        $results = $this->api->search('Users');
    }
}

Your usage is not wrong.你的用法没有错。 But, this usage stands against Dependency Injection.但是,这种用法反对依赖注入。 You don't need to use custom service provider.您不需要使用自定义服务提供程序。 But you can inject RestClient by using Laravel's class registration.但是你可以通过使用 Laravel 的类注册来注入 RestClient。

Here is an example from Laravel's documentation.这是 Laravel 文档中的一个示例。 You can setup RestClient here and you can inject it to RestApiService as well.您可以在此处设置 RestClient,也可以将其注入 RestApiService。

$this->app->singleton(Connection::class, function ($app) {
    return new Connection(config('riak'));
});

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

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