Common.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. namespace app\common\service\Oss;
  3. use Exception;
  4. use OSS\OssClient;
  5. use RuntimeException;
  6. use think\Config;
  7. class Common
  8. {
  9. protected $_ossClient = null;
  10. protected $_endpoint = '';
  11. protected $_accessKeyId = '';
  12. protected $_accessKeySecret = '';
  13. protected $_bucket = '';
  14. public function __construct($bucket = ''){
  15. $this->_endpoint = Config::get('OSS_ENDPOINT');
  16. $this->_accessKeyId = Config::get('OSS_ACCESS_KEY_ID');
  17. $this->_accessKeySecret = Config::get('ACCESS_KEY_SECRET');
  18. $this->setBucketName(!empty($bucket) ? $bucket : Config::get('ALIYUN_OSS_BUCKET'));
  19. if (is_file(EXTEND_PATH.'OSS/autoload.php')) {
  20. require_once EXTEND_PATH.'OSS/autoload.php';
  21. }
  22. $this->getOssClient();
  23. }
  24. /**
  25. * 切换OSS Bucket
  26. * @param string $bucketName
  27. */
  28. public function setBucketName(string $bucketName) {
  29. $this->_bucket = $bucketName;
  30. }
  31. public function getBucketName() {
  32. return $this->_bucket;
  33. }
  34. /**
  35. * 根据Config配置,得到一个OssClient实例
  36. * @return OssClient
  37. */
  38. public function getOssClient() {
  39. if (empty($this->_ossClient)) {
  40. try {
  41. $this->_ossClient = new OssClient($this->_accessKeyId, $this->_accessKeySecret, $this->_endpoint, false);
  42. } catch (Exception $e) {
  43. throw new RuntimeException($e->getMessage());
  44. }
  45. }
  46. return $this->_ossClient;
  47. }
  48. }