CTranslate.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * FecShop file.
  4. *
  5. * @link http://www.fecshop.com/
  6. * @copyright Copyright (c) 2016 FecShop Software LLC
  7. * @license http://www.fecshop.com/license/
  8. */
  9. namespace fec\helpers;
  10. use Yii;
  11. /**
  12. * @author Terry Zhao <2358269014@qq.com>
  13. * @since 1.0
  14. */
  15. class CTranslate
  16. {
  17. const CURRENT_LANGUAGE = 'current_language';
  18. public static $current_language;
  19. # 翻译
  20. # 使用前需要配置:
  21. /*
  22. 'i18n' => [
  23. 'translations' => [
  24. '*' => [
  25. 'class' => 'yii\i18n\PhpMessageSource',
  26. 'basePath' =>'@frontend/language', # 翻译语言的路径
  27. 'sourceLanguage' => 'en_US', # 默认语言
  28. 'fileMap' => [
  29. 'companie' => 'companie.php', # 翻译文件
  30. ],
  31. ],
  32. ],
  33. ],
  34. */
  35. # 1.在使用前,需要设置当前的语言 CTranslate::setCurrentLanguage($language);
  36. # 2.当然,也可以不设置语言,在本函数中传递语言参数到这个函数中
  37. # 语言格式为:en_US es_ES de_DE fr_FR 等
  38. # 如果不设置语言,默认为英语语言
  39. #
  40. # 使用例子:Translate::__('my %s is very %s',array('son','big'));
  41. public static function __($text,$arr = array(),$language='',$file=''){
  42. if(!$file){
  43. $file = 'companie';
  44. }
  45. if(!$language){
  46. $language = self::getCurrentLanguage();
  47. }
  48. Yii::$app->language = $language;
  49. $gText = Yii::t($file, $text);
  50. if(!empty($arr)){
  51. foreach($arr as $a){
  52. $gText = preg_replace('/%s/',$a,$gText,1);
  53. }
  54. }
  55. return $gText;
  56. }
  57. # 2.得到当前的language
  58. public static function getCurrentLanguage(){
  59. if(!self::$current_language){
  60. $language = CSession::get(self::CURRENT_LANGUAGE);
  61. if(!$language){
  62. $language = 'en_US';
  63. }
  64. self::$current_language = $language;
  65. }
  66. return self::$current_language;
  67. }
  68. # 3.设置当前的language
  69. public static function setCurrentLanguage($language){
  70. CSession::set(self::CURRENT_LANGUAGE,$language);
  71. }
  72. }