Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/EmptyTag/158.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
CakePHP 3.x-根据区域设置获取数据库字段_Cakephp_Internationalization_Translation_Locale_Cakephp 3.0 - Fatal编程技术网

CakePHP 3.x-根据区域设置获取数据库字段

CakePHP 3.x-根据区域设置获取数据库字段,cakephp,internationalization,translation,locale,cakephp-3.0,Cakephp,Internationalization,Translation,Locale,Cakephp 3.0,我开发了一个多语言网站。数据库中同时使用了4种以上的语言。它始终遵循以下方案: 字段%lang% 例如id | title | title | de | description | en | description | de 由于它非常简单,我想写一个函数,我可以在控制器和视图中使用(全局实体?),以保持代码的干性 //function public function __($field, $language = null){ if( $language === null ){

我开发了一个多语言网站。数据库中同时使用了4种以上的语言。它始终遵循以下方案: 字段%lang%

例如id | title | title | de | description | en | description | de

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

//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
问题是,我不知道在没有刹车惯例的情况下在哪里实现它。我在考虑实体,但据我所知,没有适用于所有模型的“全局”实体

欢迎提出意见和建议


Mike

\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');
        }

    }

}

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

namespace App\Model\Entity;

class User extends AppEntity {

} ;

?>