PHP code example of yunadmin / yunstorage

1. Go to this page and download the library: Download yunadmin/yunstorage library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yunadmin / yunstorage example snippets


use Yunadmin\YunStorage\Storage;

// 1. 准备配置 (实际项目从数据库或 config 读取)
$config = [
    'bucket'     => 'my-bucket',
    'access_key' => 'your-access-key',
    'secret_key' => 'your-secret-key',
    'domain'     => 'oss-cn-hangzhou.aliyuncs.com',
];

// 2. 创建 Driver 实例
$storage = Storage::make('aliyun', $config);

// 3. 上传本地文件
if ($storage->upload('/tmp/avatar.jpg', 'images/avatar.jpg')) {
    $url = $storage->getObjectUrl('images/avatar.jpg');
    echo "上传成功, 访问地址: {$url}";
} else {
    echo "上传失败: " . $storage->getError();
}

// 4. 抓取远程 URL 资源到对象存储
$storage->fetch('https://example.com/photo.png', 'images/photo.png');

// 5. 删除对象
$storage->delete('images/avatar.jpg');

Storage::extend('huawei', \app\extend\ObsDriver::class);
$storage = Storage::make('huawei', $config);

$config = [
    'bucket'        => 'your-bucket',                     // Bucket 名
    'access_key'    => 'your-access-key-id',              // AccessKey ID
    'secret_key'    => 'your-access-key-secret',          // AccessKey Secret
    'domain'        => 'oss-cn-hangzhou.aliyuncs.com',    // Endpoint (不含 bucket 前缀, V4 会自动从中解析 region)
    'region'        => '',                                 // 可选, 显式指定 (如 cn-hangzhou), 默认从 endpoint 解析
    'custom_domain' => '',                                 // 可选, 如 https://cdn.example.com
];

$config = [
    'bucket'        => 'your-bucket-1250000000',          // Bucket 名 (含 APPID 后缀)
    'region'        => 'ap-guangzhou',                     // 区域代号
    'access_key'    => 'your-secret-id',                   // SecretId
    'secret_key'    => 'your-secret-key',                  // SecretKey
    'domain'        => '',                                   // 可选, 留空则自动拼接
    'custom_domain' => '',                                   // 可选, 如 https://cdn.example.com
];

$config = [
    'bucket'        => 'your-bucket',                       // Bucket 名
    'access_key'    => 'your-access-key',                  // AK
    'secret_key'    => 'your-secret-key',                  // SK
    'region'        => 'z0',                                // 区域: z0/z1/z2/na0/as0
    'custom_domain' => 'https://cdn.example.com',          // 访问域名 (必须配置)
];

$config = [
    'bucket'        => 'your-bucket',                       // Bucket 名
    'region'        => 'gz',                                // 区域: gz/bj/su
    'access_key'    => 'your-access-key',                  // AK
    'secret_key'    => 'your-secret-key',                  // SK
    'domain'        => '',                                   // 可选, 留空则自动拼接
    'custom_domain' => '',                                   // 可选, 如 https://cdn.example.com
];

use Yunadmin\YunStorage\Storage;
use think\facade\Db;

// 从数据库读取存储配置
$channel = Db::name('storage')->where('status', 1)->find();
$config = json_decode($channel['params'], true) + [
    'bucket'     => $channel['bucket'],
    'access_key' => $channel['access_key'],
    'secret_key' => $channel['secret_key'],
    'domain'     => $channel['domain'],
    'region'     => $channel['region'] ?? '',
];

$storage = Storage::make($channel['channel'], $config);
$storage->upload($file->getPathname(), 'uploads/' . $file->hashName());

namespace app\common\service\storage\engine;

use Yunadmin\YunStorage\Storage;

class Aliyun extends Server
{
    private $storage;

    public function __construct($config)
    {
        parent::__construct($config);
        $this->storage = Storage::make('aliyun', $config);
    }

    public function upload($save_dir = '')
    {
        $key = $save_dir . '/' . $this->getFileName();
        if ($this->storage->upload($this->getRealPath(), $key)) {
            $this->setFileUrl($this->storage->getObjectUrl($key));
            return true;
        }
        $this->error = $this->storage->getError();
        return false;
    }

    public function delete($fileName)
    {
        return $this->storage->delete($fileName);
    }

    public function fetch($url, $key = null)
    {
        return $this->storage->fetch($url, $key);
    }
}

namespace app\extend;

use Yunadmin\YunStorage\AbstractDriver;
use Yunadmin\YunStorage\Signer;

class HuaweiObsDriver extends AbstractDriver
{
    public function upload(string $localPath, string $key): bool
    {
        // 1. 校验参数
        if ($key === '' || !is_file($localPath)) {
            $this->setError($key === '' ? 'key 不能为空' : "文件不存在: {$localPath}");
            return false;
        }

        // 2. 构造请求 URL
        $host   = $this->getConfig('bucket') . '.' . $this->getConfig('domain');
        $url    = 'https://' . $host . '/' . Signer::encodePath($key);

        // 3. 签名
        $headers = [
            'Content-Type'   => $this->guessMime($localPath),
            'Content-Length' => filesize($localPath),
        ];
        $this->signRequest('PUT', $key, $host, $headers);

        // 4. 流式上传
        list($resp, $code) = $this->httpUpload($url, $localPath, [], '', $headers);
        return $code >= 200 && $code < 300
            ?: ($this->setError($this->parseError($resp) ?: "HTTP {$code}") ? false : false);
    }

    public function fetch(string $url, ?string $key): bool { /* ... */ }
    public function delete(string $key): bool { /* ... */ }

    private function signRequest(string $method, string $key, string $host, array &$headers): void
    {
        // 实现厂商的签名算法
        // ...
        $headers['Authorization'] = 'OBS ' . $this->getConfig('access_key') . ':' . $signature;
    }
}

use Yunadmin\YunStorage\Storage;

Storage::extend('huawei', \app\extend\HuaweiObsDriver::class);

$storage = Storage::make('huawei', $config);
$storage->upload('/tmp/file.jpg', 'images/file.jpg');

if (!$storage->upload($file, $key)) {
    throw new \RuntimeException('上传失败: ' . $storage->getError());
}

// 切换前
$storage = Storage::make('aliyun', $aliyunConfig);

// 切换后 (业务代码完全不变)
$storage = Storage::make('qcloud', $qcloudConfig);

$storage->upload($file, $key);  // 同样的调用