【问题标题】:CakePHP 3.x - Getting database fields depending on Locale settingsCakePHP 3.x - 根据区域设置获取数据库字段
【发布时间】:2015-07-09 12:41:23
【问题描述】:

我必须开发一个多语言网站。它在数据库中同时使用超过 4 种语言。它始终遵循方案: field_%lang%

例如。编号 |标题_zh |标题_de |描述_zh |描述_de

由于它非常简单,我正在考虑编写一个可以在控制器和视图(全局实体?)中使用的函数,以保持我的代码 DRY。

//function
public function __($field, $language = null){

    if( $language === null ){

        list( $language ) = split('_', I18n::Locale());

    }

    $newField = $field . '_' . strtolower( $language );

    if( $this->has( $newField ) ){
        return $this->{ $newField };
    }else{
        throw new NotFoundException('Could not find "' . $newField . '" field');
    }

}

//usage
$result->__('title'); //returns title_en depending on Locale
$result->__('title', 'de'); //always returns title_de

问题是我不知道在没有制动约定的情况下在哪里实施它。我在考虑实体,但据我所知,没有适用于所有模型的“全局”实体?

欢迎所有想法和建议!

迈克

【问题讨论】:

  • 为什么不把它放在你所有实体的某种超类中呢?我不明白为什么它会打破惯例。
  • 是的,但是是否存在所有实体的超类?在哪里?

标签: cakephp internationalization translation locale cakephp-3.0


【解决方案1】:

\Cake\ORM\Entity 是您所有实体的基类,您不会修改内置的 CakePHP 类,但没有什么能阻止您创建自己的超类。

我们称它为AppEntity,只需在src/Model/Entity 下创建一个AppEntity.php 文件并将您的代码放入其中:

<?php

namespace App\Model\Entity;
use Cake\I18n\I18n;
use Cake\Network\Exception\NotFoundException;

class AppEntity extends \Cake\ORM\Entity {

    public function __($field, $language = null){

        if( $language === null ){

            list( $language ) = split('_', I18n::Locale());

        }

        $newField = $field . '_' . strtolower( $language );

        if( $this->has( $newField ) ){
            return $this->{ $newField };
        }else{
            throw new NotFoundException('Could not find "' . $newField . '" field');
        }

    }

}

然后,当你创建一个实体类时,你扩展\Cake\ORM\Entity而不是扩展AppEntity

<?php

namespace App\Model\Entity;

class User extends AppEntity {

} ;

?>

【讨论】:

    猜你喜欢
    • 2016-02-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    • 2018-05-26
    相关资源
    最近更新 更多