Negotiating locales - nicer urls - automatic routes - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=11) +--- Thread: Negotiating locales - nicer urls - automatic routes (/showthread.php?tid=78765) |
Negotiating locales - nicer urls - automatic routes - versigtm - 03-08-2021 Hi there! I thought I'd share some pieces of code with you about localization, because this has been one of my issues with CodeIgniter, that I solved in a more elegant way than using locales in the url & defining routes all the time. I'll be using locale negotiation, the cookie helper, and the session library (partially, because I am still more comfortable using the $_SESSION variable). 1. First I needed to configure the App to handle more locales: File: app\Config\App.php - the example is based on my needs for an app that runs by default in Romanian, but feel free to change it to whatever suits your needs PHP Code: public $defaultLocale = 'ro'; 2. Then, I altered app\Controllers\BaseController.php - which is extended in all the controllers I used: PHP Code: //load cookie helper I also changed the initController function as follows: PHP Code: //initialize session 3. Then, I created the controller app\Controllers\Locale.php to change the selected locale, for users who want to change to another locale than the one negotiated by the browser: PHP Code: <?php The redirect view - app\Views\redirect.php: Code: <!DOCTYPE html> 4. Finally, the only thing you need to use now is the LOCALE constant as the third parameter, when calling the lang() function. PHP Code: <?=lang('label.defined.in.Language.folder',[],LOCALE)?> And here's how it works. When visiting a page that extends BaseController:
Happy coding! |