CakePHP 3.x - 根据区域设置获取数据库字段
CakePHP 3.x - Getting database fields depending on Locale settings
我要开发一个多语言网站。它有4种以上的语言同时用于数据库。它总是遵循以下方案:
field_%lang%
ex. id | title_en | 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
问题是我不知道在没有制动约定的情况下在哪里实施它。我在考虑实体,但据我所知,没有适用于所有模型的 "global" 实体?
欢迎所有想法和建议!
麦克
\Cake\ORM\Entity
是所有实体的基础 class,您不会修改内置的 CakePHP class 但没有什么能阻止您创建自己的超级 class.
我们称它为 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');
}
}
}
然后,当您创建实体 class 时,您不会扩展 \Cake\ORM\Entity
,而是扩展 AppEntity
:
<?php
namespace App\Model\Entity;
class User extends AppEntity {
} ;
?>
我要开发一个多语言网站。它有4种以上的语言同时用于数据库。它总是遵循以下方案: field_%lang%
ex. id | title_en | 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
问题是我不知道在没有制动约定的情况下在哪里实施它。我在考虑实体,但据我所知,没有适用于所有模型的 "global" 实体?
欢迎所有想法和建议!
麦克
\Cake\ORM\Entity
是所有实体的基础 class,您不会修改内置的 CakePHP class 但没有什么能阻止您创建自己的超级 class.
我们称它为 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');
}
}
}
然后,当您创建实体 class 时,您不会扩展 \Cake\ORM\Entity
,而是扩展 AppEntity
:
<?php
namespace App\Model\Entity;
class User extends AppEntity {
} ;
?>