cakephpinternationalizationpocakephp-3.3

CakePHP 3.3 tables dedicated for different data based on the selected language


I have a non-standard question to CakePHP 3.3. Let's imagine that in my database I have two tables: A and B (both are identical, first is dedicated for data in the first language, second is dedicated for data in the second language).

I correctly coded the whole website for table A (table B is not yet in use). Additionally, I implemented the .po files mechanizm to switch the language of the interface. The language of the inteface switches correctly.

How can I easily plug the table B - I do not want to make IF-ELSE statements in all cases because the website is getting big, and there are many operations in table A already included. Is there a possibility to somehow make a simple mapping that table A equals table B if language pl_PL is selected to en_US (through .po files)?


Solution

  • The most simple option that comes to my mind would be to inject the current locale into your existing table class, and have it set the database table name accordingly.

    Let's assume your existing table class would be called SomeSharedTable, this could look something along the lines of:

    // ...
    
    class SomeSharedTable extends Table
    {
        public function initialize(array $config)
        {
            if (!isset($config['locale'])) {
                throw new \InvalidArgumentException('The `locale` config key is missing');
            }
    
            $table = 'en_table';
            if ($config['locale'] === 'pl_PL') {
                $table = 'pl_table';
            }
            $this->table($table);
    
            // ...
        }
    
        // ...
    }
    

    And before your appplication code involves the model layer, and after it sets the locale of course (that might for example be in your bootstrap), configure the alias that you're using throughout your application (for this example we assume that the alias matches the table name):

    \Cake\ORM\TableRegistry::config('SomeShared', [
        'locale' => \Cake\I18n\I18n::locale()
    ]);
    

    Given that it's possible that the locale might not make it into the class for whatever reason, you should implement some safety measures, I've just added that basic isset() check for example purposes. Given that a wrongly configured table class could cause quite some problems, you probably want to add some checks that are a little more sophisticated.