How to load AWS SDK into CakePHP?

2019-04-28 19:49发布

问题:

I'm creating a S3 plugin for my app. In app/Plugin/S3/Controller/Component/S3Component.php I have these:

<?php 

App::import('Vendor', 'aws/aws-autoloader');

use Aws\S3\S3Client;

class S3Component extends Component {

    public function loadS3 () {
        $s3 = S3Client::factory(array(
            'key' => '',
            'secret' => ''
        ));
        return $s3;
    }

}

In my app's controller, I call it using $s3 = $this->S3->loadS3();

It throws the error Error: Class 'Aws\S3\S3Client' not found

I tried adding the line: App::uses('Vendor', 'aws/Aws/S3/S3Client'); to the component class, and removed use Aws\S3\S3Client;. It shows Error: Class 'S3Client' not found

The AWS SDK in in the folder app/Plugin/S3/Vendor/aws

I'm loading the S3 object with reference to: http://docs.aws.amazon.com/aws-sdk-php/guide/latest/quick-start.html#factory-method

Solution:

This is how my component looks like now with the help of @akirk.

<?php 

ini_set('include_path', ROOT . DS . 'lib' . PATH_SEPARATOR . ini_get('include_path'). PATH_SEPARATOR . ROOT .DS . 'app/Plugin/S3/Vendor/aws');

require ROOT . DS . 'app/Plugin/S3/Vendor/aws/aws-autoloader.php';

use Aws\S3\S3Client;

class S3Component extends Component {

    public function loadS3 () {
        $s3 = S3Client::factory(array(
            'key' => '',
            'secret' => ''
        ));
        return $s3;
    }

}

回答1:

Clearly the autoimport doesn't work. You should do it as in the tutorial, use require

require 'vendor/autoload.php';

as the autoloading mechanism shouldn't be touched by CakePHP.