如何从TranslatedCountryCodes类获取指定国家代码翻译并在Blade展示
问题分析与解决方案
你遇到的问题有两个核心原因:
commitTranslation是实例方法,不能直接通过类名静态调用(TranslatedCountryCodes::commitTranslation()这种写法错误),必须先通过getInstance()获取单例实例。- 当前
commitTranslation方法没有接收国家代码参数的逻辑,无法直接返回单个国家的翻译名称。
解决方案一:新增专用获取方法(推荐,符合单一职责)
修改TranslatedCountryCodes类,添加一个专门根据国家代码获取翻译名称的方法:
class TranslatedCountryCodes { private $translatedCodes = []; private static $instance; protected function __construct() { $this->translatedCodes = [ 'AF' => __('Afghanistan', 'countrycode', 'myproject'), 'AX' => __('Aland Islands', 'countrycode', 'myproject') ]; } // 保留原方法,用于获取完整翻译数组 public function commitTranslation() { return $this->translatedCodes; } // 新增:根据国家代码获取翻译名称 public function getCountryName(string $code) { // 存在则返回对应翻译,不存在返回空或自定义默认值 return $this->translatedCodes[$code] ?? ''; } public static function getInstance() { if (is_null(static::$instance)) { static::$instance = new static(); } return static::$instance; } }
Blade文件中的调用方式
在Blade模板中通过单例实例调用新增的方法:
{{ TranslatedCountryCodes::getInstance()->getCountryName('AF') }}
解决方案二:修改现有commitTranslation方法(兼容原有调用)
如果想保留commitTranslation方法名,可修改它的逻辑,支持可选参数:
public function commitTranslation(?string $code = null) { // 传入代码则返回对应翻译,否则返回完整数组 if ($code) { return $this->translatedCodes[$code] ?? ''; } return $this->translatedCodes; }
此时Blade中的调用方式为:
{{ TranslatedCountryCodes::getInstance()->commitTranslation('AF') }}
额外提示
- 可以为不存在的国家代码设置更友好的默认值,比如
return $this->translatedCodes[$code] ?? __('Unknown Country', 'countrycode', 'myproject'); - 如果需要频繁在Blade中使用,可封装一个全局辅助函数,简化调用:
之后在Blade中直接写function country_name(string $code) { return TranslatedCountryCodes::getInstance()->getCountryName($code); }{{ country_name('AF') }}即可。
内容的提问来源于stack exchange,提问作者in2d
相关产品推荐
相关产品推荐

