How to work with auto routing and languages in CI4? - rodrigoguariento - 09-17-2022
Hi, I've enabled auto routing ( https://codeigniter.com/user_guide/incoming/routing.html#auto-routing-improved ) in my CI4 project, and before start work with Localization ( https://codeigniter.com/user_guide/outgoing/localization.html#working-with-locales ) I was calling my controller method like this: http://mydomain.com/mycontroller/someaction , but now with Localization on, I'm using two languages: en, pt-BR. To call the same URL in the right way would be http://mydomain.com/pt-BR/mycontroller/someaction, but working with auto routing and Localization, this URI with "locale" (pt-BR or en) does not work. Did I forget something? What is the right way to work with Location + auto routing improved in CI4? Thanks.
RE: How to work with auto routing and languages in CI4? - kenjis - 09-17-2022
The auto routing does not support localization. It does nothing for localization.
I recommend you use the defined route with locale:
https://codeigniter.com/user_guide/outgoing/localization.html#in-routes
RE: How to work with auto routing and languages in CI4? - InsiteFX - 09-18-2022
For localization see this tutorial.
Creating a multilingual website with CodeIgniter 4 (part 1)
Creating a multilingual website with CodeIgniter 4 (part 2)
RE: How to work with auto routing and languages in CI4? - rodrigoguariento - 09-30-2022
Thank you! Gradually I am understanding the difference between CI3 and CI4.
RE: How to work with auto routing and languages in CI4? - devo - 09-17-2024
(09-18-2022, 12:07 AM)InsiteFX Wrote: For localization see this tutorial.
Creating a multilingual website with CodeIgniter 4 (part 1)
Creating a multilingual website with CodeIgniter 4 (part 2) The link is no longer accessible, are there any other references?
RE: How to work with auto routing and languages in CI4? - ozornick - 09-17-2024
IncludeBeer.com blog is closed... sorry!
Project closed?
RE: How to work with auto routing and languages in CI4? - InsiteFX - 09-17-2024
I made a pdf of the web site so I have them here.
NOTE: All rights belong to the respectful owner!
PDF
IncludeBeer - Creating a multilingual website with CodeIgniter
RE: How to work with auto routing and languages in CI4? - devo - 09-17-2024
(09-17-2024, 10:01 PM)InsiteFX Wrote: I made a pdf of the web site so I have them here.
NOTE: All rights belong to the respectful owner!
PDF
IncludeBeer - Creating a multilingual website with CodeIgniter
thank you so much
RE: How to work with auto routing and languages in CI4? - InsiteFX - 09-18-2024
These are the changes I made for it to work with CodeIgniter v4.5.5.
You will need to change a couple of things that do not work any more.
1) The BaseController new code.
Code: /**
* E.g.: $this->session = \Config\Services::session();
* Ensure that the session is started and running
*/
if (session_status() == PHP_SESSION_NONE) {
$this->session = Services::session();
}
$config = new App();
$this->viewData['page'] = '';
$this->viewData['locale'] = $this->request->getLocale();
$this->viewData['supportedLocales'] = $config->supportedLocales;
/**
* Used also in the html file.
*
*<?php
* $locale = session()->get('locale');
* ?>
* <!doctype html>
* <html lang="<?= $locale; ?>" data-bs-theme="auto">
*/
session()->set('locale', $this->request->getLocale());
2) Changes to the Localize Filter Class.
Code: <?php
namespace App\Filters;
use CodeIgniter\Exceptions\PageNotFoundException;
use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
use Config\App;
/**
* Class Localize
*
* @package App\Filters
*/
class Localize implements FilterInterface
{
/**
* Class properties go here.
* -------------------------------------------------------------------
*
* public, private, protected, static and const.
*/
/**
* @var mixed
*/
private static mixed $newLocale;
/**
* @var string
*/
private string $strTmp;
/**
* before()
* -------------------------------------------------------------------
*
* Do whatever processing this filter needs to do.
* By default, it should not return anything during
* normal execution. However, when an abnormal state
* is found, it should return an instance of
* CodeIgniter\HTTP\Response. If it does, script
* execution will end and that Response will be
* sent back to the client, allowing for error pages,
* redirects, etc.
*
* @param RequestInterface $request
* @param null $arguments
* @return RedirectResponse|void
*/
public function before(RequestInterface $request, $arguments = null)
{
log_message('debug', "FilterLocalize --- start ---");
$userLocale = '';
$uri = $request->getUri();
$segments = array_filter($uri->getSegments());
$nbSegments = count($segments);
log_message('debug', "FilterLocalize - {$nbSegments} segments = " . print_r($segments, true));
if ($nbSegments == 2) {
$userLocale = $segments['1'];
}
log_message('debug', "FilterLocalize - Visitor's locale $userLocale");
$config = new App();
// If the user's language is not a supported language, take the default language
$locale = in_array($userLocale, $config->supportedLocales) ? $userLocale : $config->defaultLocale;
log_message('debug', "FilterLocalize - Selected locale $locale");
// If we request /, redirect to /{locale}
if ($nbSegments == 0) {
log_message('debug', "FilterLocalize - Redirect / to /{$locale}");
log_message('debug', "FilterLocalize --- end ---");
return redirect()->to("/{$locale}");
}
log_message('debug', "FilterLocalize - segments[0] = " . $segments[0]);
// If the first segment of the URI is not a valid locale, trigger a 404 error
if ( ! in_array($locale, $config->supportedLocales)) {
log_message('debug', "FilterLocalize - ERROR Invalid locale '{$locale}'");
log_message('debug', "FilterLocalize --- end ---");
throw PageNotFoundException::forPageNotFound();
}
log_message('debug', "FilterLocalize - Valid locale '$locale'");
log_message('debug', "FilterLocalize --- end ---");
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Do something here
}
} // End of Localize Filter Class.
/**
* -----------------------------------------------------------------------
* Filename: Localize.php
* Location: ./app/Filters/Localize.php
* -----------------------------------------------------------------------
*/
And for those that want it here my Bootstrap 5.3.3 html NavBar code for a Language DropDown selection.
PHP Code: <ul class="navbar-nav flex-row flex-wrap ms-xxl-auto"> <!-- DropDown for Language selection Component --> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false"> <i class="bi bi-globe"> <?= lang("Languages.languageName_$locale"); ?> </i> </a>
<!-- Loop through Languages and build links --> <ul class="dropdown-menu dropdown-menu-end text-small shadow"> <?php foreach ($supportedLocales as $supLocale): ?> <li class="nav-item"> <a class="dropdown-item<?= setActive($supLocale, $locale); ?>" href="<?= $supLocale ?>"> <?= lang("Languages.languageName_$supLocale"); ?> </a> </li> <?php endforeach; ?> </ul> </li> <!-- End of DropDown Language Section Component -->
I moved all blog Language code to blog.php see below English only you will need to create the rest.
Code: <?php
/**
* Blog - English
*
* Direction: left to right LTR
*/
return [
// Header
'title' => "Welcome to our Blog.",
'metaDescription' => "Example of a multilingual website made with CodeIgniter",
'metaKeywords' => "CodeIgniter, language, example",
// Blog
'aboutTitle' => "About",
'aboutText' => "Hello, here is an example of a multilingual blog.",
'noArticles' => "No articles",
'readMore' => "Read more",
];
/**
* -----------------------------------------------------------------------
* Filename: Blog.php
* Location: ./app/Language/en/Blog.php
* -----------------------------------------------------------------------
*/
I moved all Language code for the Bootstrap DropDown to languages.php
PHP Code: <?php
/** * Languages - English * * For Language DropDown with Flags. * * Direction: left to right * * In total there are 12 Right to Left languages, including * * Arabic, Aramaic, Azeri, Divehi, Fula, Hebrew, Kurdish, * N'ko, Persian, Rohingya, Syriac, and Urdu * */ return [ 'languageName_ar' => "earabiun", // Arabic / right to left RTL 'languageName_bg' => "български", // Bulgarian 'languageName_bn' => "বাংলা", // Bengali 'languageName_bs' => "bosanski", // Bosnian 'languageName_cs' => "čeština", // Czech 'languageName_de' => "Deutsch", // German 'languageName_el' => "ελληνικά", // Greek 'languageName_en' => "English", // English Default 'languageName_es' => "Español", // Spanish 'languageName_fa' => "فارسی", // Persian / right to left RTL 'languageName_fr' => "Français", // French 'languageName_hu' => "magyar", // Hungarian 'languageName_id' => "indonéz", // Indonesian 'languageName_it' => "Italiano", // Italian 'languageName_ja' => "日本語", // Japanese 'languageName_ko' => "韓国人", // Korean 'languageName_lt' => "lietuvių", // Lithuanian 'languageName_lv' => "latviski", // Latvian 'languageName_ml' => "മലയാളം", // Malayalam 'languageName_nl' => "Nederlands", // Dutch 'languageName_no' => "norsk", // Norwegian 'languageName_pl' => "Polski", // Polish 'languageName_pt' => "Português (Portugal)", // Portuguese (Portugal) 'languageName_pt-BR' => "Português (Brasil)", // Portuguese (Brazil) 'languageName_ro' => "română", // Romanian 'languageName_ru' => "rusă", // Russian 'languageName_si' => "සිංහල", // Sinhala 'languageName_sk' => "slovenský", // Slovak 'languageName_sr' => "српски", // Serbian 'languageName_sv-SE' => "svenska", // Swedish 'languageName_ta' => "தமிழ்", // Tamil 'languageName_th' => "แบบไทย", // Thai 'languageName_tr' => "Türkçe", // Turkish 'languageName_uk' => "українська", // Ukrainian 'languageName_vi' => "Tiếng Việt", // Vietnamese 'languageName_zh-CN' => "中文(简体)", // Chinese (Simplified) 'languageName_zh-TW' => "中文(繁體)", // Chinese (Traditional) Taiwan ];
/** * ----------------------------------------------------------------------- * Filename: Languages.php * Location: ./app/Language/en/Languages.php * ----------------------------------------------------------------------- */
RE: How to work with auto routing and languages in CI4? - Vespa - 11-16-2024
Really interesting and useful, thanks for sharing this code.
InsiteFX, using the following code in BaseController:
Code: if (session_status() == PHP_SESSION_NONE) {
$this->session = Services::session();
}
I get the error: Class "App\Controllers\Services" not found.
Also:
Code: $config = new App();
Give me the error: Class "App\Controllers\App" not found
Any hint to fix this?
Thanks a lot for your time
|