Home > Back-end >  Codeigniter 4 how to load a configuration file from BaseController to use it on all pages
Codeigniter 4 how to load a configuration file from BaseController to use it on all pages

Time:02-12

In my BaseController I have tried to load my configuration file in various ways, but I cannot find the values

Inside the initController function I tried:

$this->myconfig = new \Config\MyConfig;
or
$myconfig = config('\Config\\MyConfig');
or
$myconfig = config('MyConfig');
or
$this->myconfig = config('MyConfig');

None of these work

This is my MyConfig test configuration file located in the Config folder

namespace Config;

use CodeIgniter\Config\BaseConfig;

class MyConfig extends BaseConfig
{
    public $ada_default_lang = 'en';
    public $ada_site_name = 'Site name';
}

CodePudding user response:

You don't need to extend your BaseController at all.

Just create your MyConfig.php files following the upgrade docs:

In CI4, the configurations are now stored in classes which extend CodeIgniter\Config\BaseConfig.

which you do correctly:

<?php
    namespace Config;
    
    use CodeIgniter\Config\BaseConfig;
    
    class MyConfig extends BaseConfig
    {
        public $ada_default_lang = 'en';
        public $ada_site_name = 'Site name';
    }

now to access your $ada_default_lang in any controller, you just have to call it inside a controller method with e.g.:

$lang= config('MyConfig')->ada_default_lang );
die($lang); // would halt the program and output 'en'

which corresponds to the CI3.x way of something like: $this->config->item('ada_default_lang ');

  • Related