Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to autoload a self made config file in codeigniter 4?

I am unable to load my own config file. How can I autoload or manual load this file this?

    $psr4 = [
        'Config'                     => APPPATH.'Config',
        APP_NAMESPACE                => APPPATH,                // For custom namespace
        'App'                        => APPPATH,                // To ensure filters, etc still found,
        'Tests\Support'              => TESTPATH.'_support',    // So custom migrations can run during testing
    ];
like image 496
Parag Dhali Avatar asked Oct 18 '25 14:10

Parag Dhali


2 Answers

Create your configuration file in the folder /application/Config and define the class in the file SomeConfig.php like this.

<?php namespace Config;

class SomeConfig extends \CodeIgniter\Config\BaseConfig
{
    public $foo  = 'This is foo';
    public $bar = 'This is bar';
}

You "load" the class with this

$someConfig = new \Config\SomeConfig();

And you then use it with:

$fooMessage = $someConfig->foo;
$barMessage = $someConfig->bar;

I don't have to do anything to /application/Config/Autoload.php

Don't confuse "autoloading" in CI v4 with the CI v3 feature of "Auto-loading Resources". They are altogether different things!

In v4 "autoloading" is about finding files based on the class namespace.

In v3 it is a feature that causes a class to be initialized (loaded) automatically when the framework is being started.

like image 166
DFriend Avatar answered Oct 22 '25 04:10

DFriend


@DFriend is right, I just can't find anything related to autoload config. But we can add this in the initController function in the \App\Controllers\BaseController, like below:

public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        //--------------------------------------------------------------------
        // Preload any models, libraries, etc, here.
        //--------------------------------------------------------------------
        // E.g.: $this->session = \Config\Services::session();
        $this->config = \Config\Services::YOUR_CONFIG_CLASS();
    }
like image 38
kelvin Avatar answered Oct 22 '25 06:10

kelvin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!