You can set up content negotiation to happen automatically by setting two additional settings in app/Config/App.php. The first value tells the Request class that we do want to negotiate a locale, so simply set it to true:
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
// ...
public bool $negotiateLocale = true;
public array $supportedLocales = ['en', 'es', 'fr-FR'];
// ...
}
Model
public function setLocale($lang)
{
if(isset($lang))
$this->lang = $lang;
}
public function getText()
{
$rows = $this->findAll();
$text = [];
foreach ($rows as $row) {
if ($this->lang === 'en') {
$text[$row->name] = $row->en;
} elseif ($this->lang === 'hk') {
$text[$row->name] = $row->hk;
}
}
return $text;
}
lang_helper
function Text($text){
$model = model('App\Models\LanguageModel');
$session = \Config\Services::session();
$model->setLocale($session->lang);
$lang = $model->getText();
if(isset($lang[$text])){
return $lang[$text];
}else{
return $text;
}
}
LanguageController
public function switch()
{
$session = session();
$locale = $this->request->getLocale();
$session->remove('lang');
$session->set('lang',$locale);
return redirect()->back();
}
Route
$routes->get('/lang/{locale}', 'LanguageController::switch');