Call to S3Client::setRegion() fails

1.2k views Asked by At

I'm using "aws/aws-sdk-php": "3.0.3" via composer to access some S3 buckets in different regions, but I can't seem to get S3Client to change regions using the setRegion() function without it generating the error:

PHP Catchable fatal error: Argument 2 passed to Aws\AwsClient::getCommand() must be of the type array, string given, called in vendor/aws/aws-sdk-php/src/AwsClient.php on line 166 and defined in vendor/aws/aws-sdk-php/src/AwsClient.php on line 210

Code:

foreach($buckets as $bucket) {
    echo 'foo' . PHP_EOL;
    $loc = $s3->getBucketLocation(['Bucket' => $bucket])['LocationConstraint'];
    var_dump($loc);
    $s3->setRegion($loc);
    echo 'bar' . PHP_EOL;
    $years = $s3->listObjects([
        'Bucket'    => $bucket,
        'Delimiter' => '/'
    ]);
    var_dump($bucket, $years);
}

Output:

foo
string(9) "us-east-1"
PHP Catchable fatal error:  {snip}

Notes:

edit

As @giaour said, S3Client::setRegion() no longer exists in the v3 client, and the documentation I'had linked was for v2. [I have no idea why it's marked as 'latest']

Here's the code that I had implemented as a workaround, which just now levelled up to 'canonical':

protected function s3($region='us-west-2') {
    if( ! isset($this->_clients[$region]) ) {
        $this->_clients[$region] = new Aws\S3\S3Client([
            'version' => $this->_aws_version,
            'region'  => $region,
            'credentials' => $this->credentials
        ]);
    }
    return $this->_clients[$region];
}

And then:

foreach($buckets as $bucket) {
    $region = $this->s3()->getBucketLocation(['Bucket' => $bucket])['LocationConstraint'];
    $s3 = $this->s3($region);
    ...
}
1

There are 1 answers

1
giaour On BEST ANSWER

setRegion isn't a supported method in the version of the AWS SDK you're using. (The docs you linked to are for v2 of the SDK.)

You can create a new client and pass in the region in the constructor, e.g., new Aws\S3\S3Client(['version' => $s3->getApi()->getApiVersion(), 'region' => $loc]).