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

Laz*_*Guy 5 php singleton

所以,我想用单例创建一个客户端基本 URL。

这是我的 GuzzleClient.php,其中包含基本 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() 
    {}
}
Run Code Online (Sandbox Code Playgroud)

这是我应该放置基本网址的地方

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);
                }
            }
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

我坚持如何将 GuzzleClient 中的方法放入此代码中。谢谢

Gir*_*ish 0

inharit GuzzleClient类到CardTypeAPIAccessor,并检查是否$client不是instanceof GuzzleClient然后将访问对象分配到$this->client

class CardTypeAPIAccessor extends GuzzleClient
{
    private $client;

    public function __construct($client) 
    {
      if($client instanceof GuzzleClient){
          $this->client = $client              
      }else{
          $this->client = parent::getClient();

      }  


    }
}
Run Code Online (Sandbox Code Playgroud)