PHP如何实现Translation类同时支持直接返回结果和方法链式调用
PHP翻译类双调用模式优雅实现方案
<?php namespace App\Api; use App\Api\Helper\HasHtml; class Translation { use HttpRequest, HasHtml, ManageTranslations; public string $from = 'DE'; public string $to = 'EN'; public string $text = ''; // 翻译结果缓存,避免重复发起请求 protected ?string $translationResult = null; public function __construct(string $text = '') { $this->text = $text; } public static function translate(string $text): self { return new static($text); } public function from(string $language): self { $this->from = $language; // 修改参数后清空缓存,确保返回最新结果 $this->translationResult = null; return $this; } public function to(string $language): self { $this->to = $language; $this->translationResult = null; return $this; } // 实际执行翻译逻辑的核心方法 protected function performTranslation(): string { if ($this->translationResult !== null) { return $this->translationResult; } // 动态构造请求参数,避免提前生成body导致修改参数不生效 $body = [ 'target_lang' => $this->to, 'source_lang' => $this->from, 'text' => $this->text, ]; // 此处替换为你的实际翻译API调用逻辑,可直接复用已有Trait中的能力 $response = $this->post('/translate/api', $body); $this->translationResult = $response->getBody()->getContents(); return $this->translationResult; } // 魔术方法:对象被当作字符串使用时自动触发翻译返回结果 public function __toString(): string { return $this->performTranslation(); } }
特性说明
- 完全兼容要求的两种调用形式:
- 直接静态调用:
echo Translation::translate('输入文本')或$result = (string)Translation::translate('输入文本'),自动使用默认的德译英规则返回结果 - 链式自定义参数:
$result = (string)Translation::translate('输入文本')->from('DE')->to('ES'),使用自定义的源/目标语言执行翻译
- 直接静态调用:
- 无冗余方法调用,文本参数从入口传入符合使用直觉
- 内置结果缓存,同一个实例不会重复发起翻译请求,修改参数后自动清空缓存避免返回旧结果
- 请求参数动态生成,不会出现提前构造body导致参数修改不生效的问题
注:如果场景中直接将返回值作为字符串使用(如输出、拼接字符串、存入字符串类型字段),PHP会自动触发__toString方法,无需手动加(string)强转
内容的提问来源于stack exchange,提问作者Sebastian Rush
相关产品推荐
相关产品推荐

