douying6206 2014-12-12 04:31
浏览 22
已采纳

PHP:使用singleton设置客户端基本URL

So, I want to create a client base URL with singleton.

This is my GuzzleClient.php which is containing the base URL

<?php

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class GuzzleClient {
    public static function getClient()
    {
        static $client = null;
        if (null === $client) 
        {
            $client = new Client([
                'base_url' => 'http://localhost:8080/task_manager/v1/',
            ]);
        }

        return $client;
    }


    private function __construct() 
    {}
}

And this one is where I should put the base url

require_once 'GuzzleClient.php';

class CardTypeAPIAccessor 
{

    private $client;

    public function __construct($client) 
    {
        $this->client = $client;
    }

    public function getCardTypes() {
        $cardTypes = array();

        try 
        {
            //this is where base URL should be
            $response = $client->get('admin/card/type',
                ['headers' => ['Authorization' => $_SESSION['login']['apiKey']]
            ]);

            $statusCode = $response->getStatusCode();
            // Check that the request is successful.
            if ($statusCode == 200) 
            {
                $error = $response->json();
                foreach ($error['types'] as $type) 
                {
                    $cardType = new CardType();
                    $cardType->setId($type['card_type_id']);
                    $cardType->setCategory($type['category']);

                    array_push($cardTypes, $cardType);
                }
            }
        }
    }


}

I stuck with how to put the method in GuzzleClient into this code. Thanks

  • 写回答

1条回答 默认 最新

  • dousi7579 2014-12-12 04:51
    关注

    inharit GuzzleClient class into CardTypeAPIAccessor, and check if $client is notinstanceof GuzzleClient then assign access object into $this->client

    class CardTypeAPIAccessor extends GuzzleClient
    {
        private $client;
    
        public function __construct($client) 
        {
          if($client instanceof GuzzleClient){
              $this->client = $client              
          }else{
              $this->client = parent::getClient();
    
          }  
    
    
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 pandas 的list追加问题
  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题