目标:让"本地磁盘 / 阿里云 OSS / 腾讯云 COS"能切换,且在后台完成、立即生效、可审计。全程用
wise-support的ExtPoint实现,不写任何if ($driver === 'gd')式的分支。
场景
业务要传头像和附件,早期只在本地磁盘。后来一个客户要求走 OSS,再过一阵另一个客户要 COS,且运维希望在后台点一下切换、失败能切回去、谁改的能查到。
硬编码写法会变成:switch ($driver) 出现在上传、缩略图、下载、清理等七八个地方,每加一个驱动改八处。扩展点把这件事拆成两半:定义方只说"这里有个位置、契约是什么",实现方只说自己符合契约。
开始之前
composer require wiseadmin/wise-support
php think service:discoverwise-support 无配置、无迁移,注册服务后即可用。此篇代码放在宿主 app/common/ 下,插件里同理(把命名空间换成 plugin\{ident}\)。
第一步:定义契约
先定"驱动要能做什么"。契约越小,实现越容易写:
namespace app\common\contract;
interface StorageDriverInterface
{
public function name(): string;
public function put(string $path, string $content): string; // 返回可访问 URL
public function get(string $path): ?string;
}三个方法够了:写入、读取、标识自己。不要在这里放"列举文件""删除目录"这类只有本地磁盘才自然的能力——那会把云端驱动逼着写空实现。
第二步:实现一个驱动
namespace app\common\storage;
use app\common\contract\StorageDriverInterface;
final class LocalDriver implements StorageDriverInterface
{
public function name(): string { return 'local'; }
public function put(string $path, string $content): string
{
$file = app()->getRootPath() . 'public/storage/' . ltrim($path, '/');
@mkdir(dirname($file), 0755, true);
file_put_contents($file, $content);
return '/storage/' . ltrim($path, '/');
}
public function get(string $path): ?string
{
$file = app()->getRootPath() . 'public/storage/' . ltrim($path, '/');
return is_file($file) ? (string) file_get_contents($file) : null;
}
}OssDriver 同理,name() 返回 'oss'。实现越多,你越会发现"契约定对了"——每个驱动都只有几十行。
第三步:定义点 + 注册实现
namespace app\common\provider;
use app\common\contract\StorageDriverInterface;
use app\common\storage\LocalDriver;
use app\common\storage\OssDriver;
use think\Service;
use wise\support\ExtPoint;
final class StorageServiceProvider extends Service
{
public function boot(): void
{
// ① 定义点:SINGLE + 契约 + 能力市场展示元数据
ExtPoint::definePoint(
'storage.driver',
ExtPoint::POLICY_SINGLE,
StorageDriverInterface::class,
[
'name' => '对象存储驱动',
'description' => '本地磁盘 / 阿里云 OSS / 腾讯云 COS 可插拔切换',
'module' => 'storage',
'category' => '存储',
'visible' => true,
]
);
// ② 注册实现:priority 越小越靠前;SINGLE 下首个注册自动成为默认 active
ExtPoint::register('storage.driver', 'local', LocalDriver::class, 100);
ExtPoint::register('storage.driver', 'oss', OssDriver::class, 50);
}
}两处容易忽略:
- 第四个参数是能力市场展示元数据。不写它,扩展点不会出现在后台能力市场,运维就"看不见这个开关"。
- 传了契约后,实现类不符合契约会在
register()时立即抛异常(fail-fast),而不是让实现静默消失。
第四步:消费方必须 fail-closed
namespace app\common\storage;
use app\common\contract\StorageDriverInterface;
use wise\support\ExtPoint;
use wise\support\context\RequestContext;
final class StorageManager
{
private ?StorageDriverInterface $resolved = null;
private string $resolvedFor = '';
public function driver(): StorageDriverInterface
{
// 请求级缓存:FPM 每请求新进程;常驻下按 RequestContext 的桶隔离
$scope = RequestContext::getRequestId();
if ($this->resolved !== null && $this->resolvedFor === $scope) {
return $this->resolved;
}
$active = ExtPoint::active('storage.driver');
if ($active === null) {
throw new \RuntimeException('没有可用的存储驱动:扩展点 storage.driver 已被全部停用');
}
$concrete = $active['concrete']; // 类名或工厂闭包
$driver = is_string($concrete) ? app()->make($concrete) : $concrete();
if (!$driver instanceof StorageDriverInterface) {
throw new \RuntimeException(
sprintf('存储驱动 [%s] 未实现 StorageDriverInterface', $active['name'])
);
}
$this->resolved = $driver;
$this->resolvedFor = $scope;
return $this->resolved;
}
public function clear(): void
{
$this->resolved = null;
$this->resolvedFor = '';
}
}三段逻辑各有理由:
- 判空并抛错:
active()在所有实现被停用时返回null,这是刻意的 fail-closed。绝不能"回退到第一个"——那等于让"停用"失效。 - 契约二次校验:
register()已校验过一次,这里防的是"用闭包注册、闭包返回了错对象"。 - 请求级缓存带作用域键:用
RequestContext::getRequestId()当键,而不是缓存到类属性里不管作用域——常驻模式下后者会串档。
业务侧调用:
$url = app(\app\common\storage\StorageManager::class)
->driver()
->put('avatar/' . $userId . '.png', $binary);第五步:后台切换(能力市场式)
if (!ExtPoint::setActive('storage.driver', 'oss', true, 'admin')) {
return $this->error('无权限变更该扩展点的活跃实现,或该实现不存在');
}
if (!ExtPoint::persistOverrides()) {
return $this->error('状态已切换,但持久化失败,刷新后可能恢复原状');
}两步分开是有意义的:setActive() 改内存,persistOverrides() 落盘。分两步才能如实告诉用户"切了但没存住",而不是假装成功。
宿主已绑定授权器(AppService 里):
ExtPoint::bindOverrideAuthorizer(function (string $point, string $name, bool $active): bool {
unset($point, $name, $active);
return (bool) app('auth')->user('admin'); // CLI / 队列无请求上下文 → false → 拒绝
});注意它是闭包而不是布尔值:写成常量 true 等于永久放行,CLI 与队列也会拿到授权。
三件必须知道的事
1. SINGLE 全停用 = active() 返回 null。 消费方必须抛错。这是"停用按钮真的有用"的唯一保证。
2. ExtPoint 注册表是进程级静态,不是请求态。 常驻模式下宿主在请求边界用 resetRequestState(true) / applyPersistedOverrides() 清理与重放;否则会出现"后台改了不生效"或"上一个请求的活跃状态串到下一个请求"。
3. 安全点只有 3 个:auth.guard、jwt.provider、connector。这三个点的活跃变更在未绑定授权器时默认拒绝,且落盘时会二次校验。你自定义的 storage.driver 不属于安全点,非安全点恒放行——所以"谁能切存储"要靠控制器权限控制,而不是指望扩展点拦截。
自查
php think service:discoverdump(\wise\support\ExtPoint::active('storage.driver')['name']); // local
dump(\wise\support\ExtPoint::all('storage.driver')); // local + oss
dump(\wise\support\ExtPoint::getUndefinedRegistrations()); // 应为空后台能力市场应能看到「对象存储驱动」;切到 oss 后 active()['name'] 变为 oss,重启进程后仍是 oss(说明已落盘)。getUndefinedRegistrations() 非空说明某个点的名字拼错了——这是最容易被忽略的自检项。