douzhi1879 2016-12-30 18:17
浏览 37
已采纳

Laravel在哪里存储配置的实例逻辑?

I am using Laravel for a Github API project.

I want to set up a generic Guzzle client instance that has been pre-configured. I need this because with about 90% of my Guzzle requests, the Guzzle client will need an access_token header and a base_uri.

// Return a new configured guzzle client.
return new Client([
    'base_uri' => 'https://api.github.com',
    'headers' => [
        'Authorization' => "token {$access_token}"
    ]
]);

I know I can bind this in the container I am currently doing it like so inside a custom middleware:

if (Auth::check()) {
    $this->app->singleton(Client::class, function() {
        // Grab the current user.
        $user = Auth::user();

        $access_token = decrypt($user->access_token);

        // Return a new configured Guzzle instance.
        return new Client([
            'base_uri' => 'https://api.github.com',
            'headers' => [
                'Authorization' => "token {$access_token}"
            ]
        ]);
    });
}

I am simply overriding the default Guzzle client with my pre-configured concrete instance. This works fine but the problem I am running into is that I can not do the following in a controller:

public function __construct(Container $container)
{
    $guzzle = $container->make(Client::class);
}

If I use the above I will simply get the default implementation of Guzzle and not my pre-configured instance. I am guessing this it because the controller's constructor runs before the middleware and is it simply not set yet.

I still want to share the property to other methods in the controller though. How could I fix this?

  • 写回答

1条回答 默认 最新

  • drep94225 2016-12-30 18:19
    关注

    I would create a new class for api interactions. In the constructor, initiate your guzzle object and then create methods for various api calls that use that guzzle object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么