Symfony S3 Service Encapsulation
Today, we’ll be integrating the Amazon S3 service into our Symfony project by utilizing the encapsulation method.
First, let’s install the S3 package via Composer.
composer require aws/aws-sdk-php
We make the necessary definitions in the env file.
//your .env file
S3_CREDENTIALS_KEY=‘your key
S3_CREDENTIALS_SECRET='your secret’
S3_REGION='your region’
S3_VERSION='your version’
S3_ENDPOINT='’
S3_USE_PATH_STYLE_ENDPOINT='’
If you’d like to use services like DigitalOcean or Minio instead of Amazon, simply defining an endpoint will be sufficient.
S3Config.php
<?php
namespace App\Service\S3;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
readonly class S3Config
{
public function __construct(
#[Autowire(env: 'S3_CREDENTIALS_KEY')]
public string $credentialKey,
#[Autowire(env: 'S3_CREDENTIALS_SECRET')]
public string $credentialSecret,
#[Autowire(env: 'S3_REGION')]
public string $region,
#[Autowire(env: 'S3_VERSION')]
public string $version,
#[Autowire(env: 'S3_ENDPOINT')]
public string $endpoint,
#[Autowire(env: 'bool:S3_USE_PATH_STYLE_ENDPOINT')]
public bool $usePathStyleEndpoint,
)
{
}
}
S3Service.php
<?php
namespace App\Service\S3;
use Aws\Credentials\Credentials;
use Aws\S3\S3Client;
readonly class S3Service
{
private S3Client $s3Client;
public function __construct(
private S3Config $config
)
{
$parameters = [
'credentials' => new Credentials($this->config->credentialKey, $this->config->credentialSecret),
'region' => $this->config->region,
'version' => $this->config->version,
'use_path_style_endpoint' => $this->config->usePathStyleEndpoint,
];
if (!empty($this->config->endpoint)) {
$parameters['endpoint'] = $this->config->endpoint;
}
$this->s3Client = new S3Client($parameters);
}
public function listBuckets(): array
{
$buckets = $this->s3Client->listBuckets();
return $buckets['Buckets'];
}
public function putObjectByBody(string $bucket, string $key, string $body): void
{
$this->s3Client->putObject([
'Bucket' => $bucket,
'Key' => $key,
'Body' => $body
]);
}
public function getObject(string $bucket, string $key): ?string
{
$result = $this->s3Client->getObject([
'Bucket' => $bucket,
'Key' => $key
]);
return $result['Body'] ?? null;
}
}
You can extend your service with additional methods based on your specific needs.
Now you can call and use our service wherever you want to define it.
See you later..