Background

這邊主要介紹一下 Laravel 怎麼跟 AWS 的服務串接. 以s3為例.

Install

The AWS Service Provider can be installed via Composer. 所以在妳的 composer.json 加入:

composer.json

{
    "require": {
        "aws/aws-sdk-php-laravel": "~3.0"
    }
}

接著run update的指令

$ php composer.phar update
or 
$ php composer update

bootstrap/app.php

$app->register(Aws\Laravel\AwsServiceProvider::class);

config/app.php

  • providers
    'providers' => array(
        // ...
        Aws\Laravel\AwsServiceProvider::class,
    )
  • aliases
    'aliases' => array(
        // ...
        'AWS' => Aws\Laravel\AwsFacade::class,
    )

To customize the configuration file, publish the package configuration using Artisan.

$ php artisan vendor:publish

app/config/aws.php

return [
    'credentials' => [
        'key'    => 'YOUR_AWS_ACCESS_KEY_ID',
        'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
    ],
    'region' => 'us-west-2',
    'version' => 'latest',
    
    // You can override settings for specific services
    'Ses' => [
        'region' => 'us-east-1',
    ],
];

這樣大概就大致上安裝完了. 記得填入你的 key & secret

Usage

upload file to s3

$s3 = AWS::createClient('s3');
$s3->putObject(array(
    'Bucket'     => 'YOUR_BUCKET',
    'Key'        => 'YOUR_OBJECT_KEY',
    'SourceFile' => '/the/path/to/the/file/you/are/uploading.ext',
    'ACL'        => 'public-read',
));

get object url

$s3 = AWS::createClient('s3');
$url = $s3->getObjectUrl($OUR_BUCKET, $YOUR_OBJECT_KEY);
echo $url;

Reference