Merge config arrays using Registrar file

37 views Asked by At

I have my main CodeIgniter 4 installation that contains a configuration file named Menu that has a setting named $menu that contains a menu structure array. I have created a reusable module with the same menu configuration file with menu options for that feature. I am attempting to merge these two arrays and assign them to the parent $menu variable within the Registrar file.

I have attempted this by calling both config file properties and using merge_array() but received an infinite loop error. Does anyone have any suggestions or an alternate method of achieving this?

Here is the code I am using:

<?php

namespace Developer\Config;

use Developer\Collectors\Developer;

class Registrar
{
    public static function Menu(): array
    {
        $app_config = config('Menu');
        $sub_config = new Developer\Config\Menu();

        $menu = array_merge($app_config->menu, $sub_config->menu);
        
        return [
            'menu' => $menu,
        ];
    }

    public static function Toolbar(): array
    {
        return [
            'collectors' => [
                Developer::class,
            ],
        ];
    }
}

Below is the error I received:

Xdebug has detected a possible infinite loop, and aborted your script with a stack depth of '256' frames
1

There are 1 answers

0
b126 On

Xdebug is right... you are indeed calling your Menu() method in a loop, from inside Menu().

You initialise it inside itself like this $sub_config = new Developer\Config\Menu();

Loop

Your code should probably look more like this :

public static function Menu(): array
    {
        $app_config = config('Menu');
        $sub_config = config('Sub-Menu');

        $menu = array_merge($app_config->menu, $sub_config->menu);
        
        return [
            'menu' => $menu,
        ];
    }