2017-08-30 117 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' 
));