I had this S3Helper class before such that, every time I called a function to any of its methods (which I haven't shown here, but which do things like upload files to s3 or get temporary s3 links), it called the getClient() method and it would make a new client every time.
Now I don't know about the performance hit on that, if calling new S3Client([]) makes http requests every time it's called, but I supposed it did so decided I'd rather just make the client once and then use the same client for future calls.
So I cached the result in a static variable, and now my getClient function checks if the cache exists first, and if it does it returns it, otherwise it makes a new client and sets the cache.
Is this a recommended PHP way of doing things? Can it be improved?
<?php // Code within app\Helpers\Helper.php
namespace App\Helpers;
use Aws\S3\S3Client;
class S3Helper {
protected static $client = null;
private static function getAuth() {
return [
'endpoint' => env('S3_ENDPOINT'),
'key' => env('S3_KEY'),
'secret' => env('S3_SECRET'),
'bucket' => env('S3_BUCKET')
];
}
private static function getClient() {
if (self::$client) return self::$client;
$auth = self::getAuth();
self::$client = new S3Client([
'region' => 'eu-west-2',
'version' => '2006-03-01',
'endpoint' => $auth['endpoint'],
'credentials' => [
'key' => $auth['key'],
'secret' => $auth['secret']
],
'use_path_style_endpoint' => true
]);
return self::$client;
}
}