使用S3使用PHP DI在PHP上传

时间:2017-08-30 00:07:53

标签: php amazon-web-services amazon-s3

我正在使用依赖注入器来设置S3的凭据:

// AWS S3 for PDF
$container['s3_pdf'] = function ($c) {
    // Only load credentials from environment variables.
    $provider = CredentialProvider::env();

    $s3 = new Aws\S3\S3Client([
        'version'     => 'latest',
        'region'      => 'ap-southeast-2',
        'credentials' => $provider
    ]);

    return $s3;
};

然后每当我想上传我要做的事情时:

$result = $this->s3_pdf->putObject(array(
    'Bucket'       => 'reports.omitted.com',
    'Key'          => 'temptest1.pdf',
    'SourceFile'   => 'assets/temp.pdf',
    'ContentType'  => 'text/plain',
    'ACL'          => 'public-read',
    'StorageClass' => 'REDUCED_REDUNDANCY',
    'Metadata'     => array(
        'param1' => 'value 1',
        'param2' => 'value 2'
    )
));

我希望能够从代码中的不同函数上传到S3,而不必每次都写入桶名称,我能够让s3_pdf容器返回仅需sourcefile的函数并运行一些代码来找出源文件&目的地和上传到S3?

我知道我可以使用一个包含此函数的类,并且在我需要S3的函数中使用该类的对象但是如果有办法可以使用依赖容器如此。

1 个答案:

答案 0 :(得分:0)

这是我建议的包装函数的最简单示例:

class WhateverYourClassIs
{
  function putObject( $key, $sourceFile )
  {
    return $this->s3_pdf->putObject(array(
      'Bucket'       => 'reports.omitted.com',
      'Key'          => $ke,
      'SourceFile'   => $sourceFile,
      'ContentType'  => 'text/plain',
      'ACL'          => 'public-read',
      'StorageClass' => 'REDUCED_REDUNDANCY',
      'Metadata'     => array(
          'param1' => 'value 1',
          'param2' => 'value 2'
      )
    ));
  }
}

或使用数组

class WhateverYourClassIs
{
  function putObject( $overloadedConfig )
  {
    $baseConfig = array(
      'Bucket'       => 'reports.omitted.com',
      'Key'          => NULL,
      'SourceFile'   => NULL,
      'ContentType'  => 'text/plain',
      'ACL'          => 'public-read',
      'StorageClass' => 'REDUCED_REDUNDANCY',
      'Metadata'     => array()
    );
    return $this->s3_pdf->putObject( array_merge_recursive( $baseConfig, $overloadedConfig ) );
  }
}

$this->putObject(array(
  'Key' => 'temptest1.pdf',
  'SourceFile' => assets/temp.pdf'
));