Include a config file inside another one

Hi again,

In K3 I tried to set my good old K2 config:

  • config.php who contain general rules.
  • config.localhost.php inherit from config + enable debug and disable cache.
  • config.my-website.local.php - vhost, just include config.localhost.php.

The vhost config work well in Kirby 2 but not in Kirby 3.

Here a simple configuration:

config.php

<?php
return [
  'current-config' => 'general-config',
];

config.localhost.php

<?php
return [
  'current-config' => 'local-config',
];

config.my-website.local.php

<?php
$config = __DIR__ . DS . 'config.localhost.php';

if (file_exists($config)):
  include $config;
endif;

Inside a template, like default.php put <?php echo $kirby->option('current-config'); ?>.
And then if you try with the vhost my-website.local, you will see “general-config” instead “local-config”.
Nothing is replaced.
I tried to put in the vhost config the same content as the local config instead of the include, this worked. So there is a problem when we include a config file. Did I miss something ?

Thanks!

Because of how it is baked, I think:

    protected function optionsFromConfig(): array
    {
        $server = $this->server();
        $root   = $this->root('config');

        Config::$data = [];

        $main   = F::load($root . '/config.php', []);
        $host   = F::load($root . '/config.' . basename($server->host()) . '.php', []);
        $addr   = F::load($root . '/config.' . basename($server->address()) . '.php', []);

        $config = Config::$data;

        return $this->options = array_replace_recursive($config, $main, $host, $addr);
    }

So what you can do:

<?php

return F::load(__DIR__ . '/config.localhost.php', []);

Wow, the solution is far from where i was looking haha.
Maybe I can suggest to simplify this and be able to do it easier ?

Thanks @texnixe again and again for all your handy help here.

@yoanm

It’s actually shorter than your original code. Note that I corrected it and added an empty array as fallback to the F::load() method.

The F::load method actually checks if the file exists and returns the fallback if not. So you don’t have to add an additional if-statement.

Ah thanks, vith the fallback it’s better.

I will also give a look on the F:: and all others tools in the doc :slight_smile:

Coming back to this once again, if you want to add custom config settings, you can use the same syntax as in the optionsFromConfig() method above:

<?php

return array_replace_recursive(F::load(__DIR__ . '/config.localhost.php', []),[
    'current-config' => 'something'
]);

And the first one can actually be simplified as in the above post, don’t know why I couldn’t make it work yesterday.

1 Like