cacheKeyPrefix = $g; $this->cache = $cache ?? new FileCacheStore(self::defaultCacheStoreDirectory()); $this->authorizers = $authorizers; $this->http = $http; } public function wechatPlatform(WechatPlatformConfig $config): WechatPlatformClient { return new WechatPlatformClient($config, $this->http, $this->cache, $this->cacheKeyPrefix); } public function wechatWxapp(WechatWxappConfig $config): WechatWxappClient { return new WechatWxappClient($config, $this->http, $this->cache, $this->cacheKeyPrefix); } public function wechatService(WechatServiceConfig $config): WechatServiceClient { return new WechatServiceClient($config, $this->http, $this->cache, $this->authorizers, $this->cacheKeyPrefix); } public function wechatPayment(WechatPaymentConfig $config): WechatPaymentClient { return new WechatPaymentClient($config, $this->http); } public function alipayPlatform(AlipayPlatformConfig $config): AlipayPlatformClient { return new AlipayPlatformClient($config, $this->http); } public function alipayPayment(AlipayPaymentConfig $config): AlipayPaymentClient { return new AlipayPaymentClient($config, $this->http); } /** 默认缓存落盘目录:`sys_get_temp_dir()` + 包级子目录名,供未显式传入 `cache` 时构造 {@see FileCacheStore}。 */ public static function defaultCacheStoreDirectory(): string { return rtrim(sys_get_temp_dir(), DIRECTORY_SEPARATOR . '/') . DIRECTORY_SEPARATOR . self::DEFAULT_CACHE_STORE_DIR_NAME; } /** * 按字符串通道创建客户端;通道名称与配置对象一一对应。 */ public function get(string $channel, ConfigInterface $config): object { return match ($channel) { 'wechat.platform' => $this->wechatPlatform($this->ensureConfig($config, WechatPlatformConfig::class, 'wechatPlatform')), 'wechat.wxapp' => $this->wechatWxapp($this->ensureConfig($config, WechatWxappConfig::class, 'wechatWxapp')), 'wechat.service' => $this->wechatService($this->ensureConfig($config, WechatServiceConfig::class, 'wechatService')), 'wechat.payment' => $this->wechatPayment($this->ensureConfig($config, WechatPaymentConfig::class, 'wechatPayment')), 'alipay.platform' => $this->alipayPlatform($this->ensureConfig($config, AlipayPlatformConfig::class, 'alipayPlatform')), 'alipay.payment' => $this->alipayPayment($this->ensureConfig($config, AlipayPaymentConfig::class, 'alipayPayment')), default => throw new SdkException('不支持的通道标识: ' . $channel), }; } /** * 校验工厂方法收到的配置对象类型。 * * @template T of object * @param class-string $expected * @return T */ private function ensureConfig(ConfigInterface $config, string $expected, string $factory): object { if (!$config instanceof $expected) { throw new SdkException($factory . ' 需要 ' . $this->shortClass($expected)); } return $config; } /** * 获取类短名,用于生成清晰的配置类型错误信息。 * * @param class-string $fqcn */ private function shortClass(string $fqcn): string { $pos = strrpos($fqcn, '\\'); return $pos === false ? $fqcn : substr($fqcn, $pos + 1); } }