2017-08-30 118 views
-1

我使用依赖注入设置S3的凭据在PHP上传:使用S3使用PHP DI

// 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功能类的一个对象的类,但我宁愿使用的依赖容器是否有办法这样做。

+0

作出新的'$这个 - > putObject()'函数,它包装'$ this-> s3_pdf-> putObject()'并注入您的配置 – Scuzzy

+0

@Scuzzy感谢您的评论。我如何将参数传递给该函数? –

+0

我建议你可以将两个数组合并在一起,你的包装函数提供了基础,并且提供了覆盖参数。请参阅array_merge(),甚至array_merge_recursive() – Scuzzy

回答

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' 
));