Search code examples
phpclasswrapperapi-key

How can I set an API key once and save it within a function?


I am working on some classes and functions. The functions fetch data from an API which requires an API key. Is it possible to set an API key once and then use it throughout the program?


// Class example
class Airport
{
    public function setClient($appId, $appKey)
    {
        $client = new GuzzleHttp\Client([
            'headers' => array(
                'resourceversion' => 'v4',
                'accept' => 'application/json',
                'app_id' => $appId, // Set this
                'app_key' => $appKey // And this
            )
        ]);
    }
}
// Other file example
require 'classes.php';

$airport = new Airport();
$airport->setClient('xxxxxxxxxxx', 'xxxxxxxx');

// Continue to use other functions without setting the API key again.

Solution

  • You can save them as properties using $this

    I'm not sure if you want to reuse the client or the app id/key, but it's pretty much the same idea either way.

    
    // Class example
    class Airport
    {
        private $appId;
        private $appKey;
        private $client;
    
        public function setClient($appId, $appKey)
        {
            $this->appId = $appId;
            $this->appKey = $appKey;
    
            $this->client = new GuzzleHttp\Client([
                'headers' => array(
                    'resourceversion' => 'v4',
                    'accept' => 'application/json',
                    'app_id' => $this->appId, // Set this
                    'app_key' => $this->appKey // And this
                )
            ]);
        }
    
        // New function that uses the client
        public function someOtherMethod()
        {
            $x = $this->client->someMethod();
        }
    
        // new function that uses the app properties
        public function anotherMethod()
        {
            $x = new Something($this->appId, $this->appKey);
        }
    }